1 /* $OpenBSD: session.c,v 1.274 2014/07/15 15:54:14 millert Exp $ */ 2 /* 3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 4 * All rights reserved 5 * 6 * As far as I am concerned, the code I have written for this software 7 * can be used freely for any purpose. Any derived versions of this 8 * software must be clearly marked as such, and if the derived work is 9 * incompatible with the protocol description in the RFC file, it must be 10 * called by a name other than "ssh" or "Secure Shell". 11 * 12 * SSH2 support by Markus Friedl. 13 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved. 14 * 15 * Redistribution and use in source and binary forms, with or without 16 * modification, are permitted provided that the following conditions 17 * are met: 18 * 1. Redistributions of source code must retain the above copyright 19 * notice, this list of conditions and the following disclaimer. 20 * 2. Redistributions in binary form must reproduce the above copyright 21 * notice, this list of conditions and the following disclaimer in the 22 * documentation and/or other materials provided with the distribution. 23 * 24 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 25 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 26 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 27 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 28 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 30 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 31 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 */ 35 36 #include "includes.h" 37 __RCSID("$FreeBSD$"); 38 39 #include <sys/types.h> 40 #include <sys/param.h> 41 #ifdef HAVE_SYS_STAT_H 42 # include <sys/stat.h> 43 #endif 44 #include <sys/socket.h> 45 #include <sys/un.h> 46 #include <sys/wait.h> 47 48 #include <arpa/inet.h> 49 50 #include <errno.h> 51 #include <fcntl.h> 52 #include <grp.h> 53 #include <netdb.h> 54 #ifdef HAVE_PATHS_H 55 #include <paths.h> 56 #endif 57 #include <pwd.h> 58 #include <signal.h> 59 #include <stdarg.h> 60 #include <stdio.h> 61 #include <stdlib.h> 62 #include <string.h> 63 #include <unistd.h> 64 65 #include "openbsd-compat/sys-queue.h" 66 #include "xmalloc.h" 67 #include "ssh.h" 68 #include "ssh1.h" 69 #include "ssh2.h" 70 #include "sshpty.h" 71 #include "packet.h" 72 #include "buffer.h" 73 #include "match.h" 74 #include "uidswap.h" 75 #include "compat.h" 76 #include "channels.h" 77 #include "key.h" 78 #include "cipher.h" 79 #ifdef GSSAPI 80 #include "ssh-gss.h" 81 #endif 82 #include "hostfile.h" 83 #include "auth.h" 84 #include "auth-options.h" 85 #include "authfd.h" 86 #include "pathnames.h" 87 #include "log.h" 88 #include "misc.h" 89 #include "servconf.h" 90 #include "sshlogin.h" 91 #include "serverloop.h" 92 #include "canohost.h" 93 #include "session.h" 94 #include "kex.h" 95 #include "monitor_wrap.h" 96 #include "sftp.h" 97 98 #if defined(KRB5) && defined(USE_AFS) 99 #include <kafs.h> 100 #endif 101 102 #ifdef WITH_SELINUX 103 #include <selinux/selinux.h> 104 #endif 105 106 #define IS_INTERNAL_SFTP(c) \ 107 (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \ 108 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \ 109 c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \ 110 c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t')) 111 112 /* func */ 113 114 Session *session_new(void); 115 void session_set_fds(Session *, int, int, int, int, int); 116 void session_pty_cleanup(Session *); 117 void session_proctitle(Session *); 118 int session_setup_x11fwd(Session *); 119 int do_exec_pty(Session *, const char *); 120 int do_exec_no_pty(Session *, const char *); 121 int do_exec(Session *, const char *); 122 void do_login(Session *, const char *); 123 #ifdef LOGIN_NEEDS_UTMPX 124 static void do_pre_login(Session *s); 125 #endif 126 void do_child(Session *, const char *); 127 void do_motd(void); 128 int check_quietlogin(Session *, const char *); 129 130 static void do_authenticated1(Authctxt *); 131 static void do_authenticated2(Authctxt *); 132 133 static int session_pty_req(Session *); 134 135 /* import */ 136 extern ServerOptions options; 137 extern char *__progname; 138 extern int log_stderr; 139 extern int debug_flag; 140 extern u_int utmp_len; 141 extern int startup_pipe; 142 extern void destroy_sensitive_data(void); 143 extern Buffer loginmsg; 144 145 /* original command from peer. */ 146 const char *original_command = NULL; 147 148 /* data */ 149 static int sessions_first_unused = -1; 150 static int sessions_nalloc = 0; 151 static Session *sessions = NULL; 152 153 #define SUBSYSTEM_NONE 0 154 #define SUBSYSTEM_EXT 1 155 #define SUBSYSTEM_INT_SFTP 2 156 #define SUBSYSTEM_INT_SFTP_ERROR 3 157 158 #ifdef HAVE_LOGIN_CAP 159 login_cap_t *lc; 160 #endif 161 162 static int is_child = 0; 163 164 /* Name and directory of socket for authentication agent forwarding. */ 165 static char *auth_sock_name = NULL; 166 static char *auth_sock_dir = NULL; 167 168 /* removes the agent forwarding socket */ 169 170 static void 171 auth_sock_cleanup_proc(struct passwd *pw) 172 { 173 if (auth_sock_name != NULL) { 174 temporarily_use_uid(pw); 175 unlink(auth_sock_name); 176 rmdir(auth_sock_dir); 177 auth_sock_name = NULL; 178 restore_uid(); 179 } 180 } 181 182 static int 183 auth_input_request_forwarding(struct passwd * pw) 184 { 185 Channel *nc; 186 int sock = -1; 187 188 if (auth_sock_name != NULL) { 189 error("authentication forwarding requested twice."); 190 return 0; 191 } 192 193 /* Temporarily drop privileged uid for mkdir/bind. */ 194 temporarily_use_uid(pw); 195 196 /* Allocate a buffer for the socket name, and format the name. */ 197 auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX"); 198 199 /* Create private directory for socket */ 200 if (mkdtemp(auth_sock_dir) == NULL) { 201 packet_send_debug("Agent forwarding disabled: " 202 "mkdtemp() failed: %.100s", strerror(errno)); 203 restore_uid(); 204 free(auth_sock_dir); 205 auth_sock_dir = NULL; 206 goto authsock_err; 207 } 208 209 xasprintf(&auth_sock_name, "%s/agent.%ld", 210 auth_sock_dir, (long) getpid()); 211 212 /* Start a Unix listener on auth_sock_name. */ 213 sock = unix_listener(auth_sock_name, SSH_LISTEN_BACKLOG, 0); 214 215 /* Restore the privileged uid. */ 216 restore_uid(); 217 218 /* Check for socket/bind/listen failure. */ 219 if (sock < 0) 220 goto authsock_err; 221 222 /* Allocate a channel for the authentication agent socket. */ 223 nc = channel_new("auth socket", 224 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1, 225 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 226 0, "auth socket", 1); 227 nc->path = xstrdup(auth_sock_name); 228 return 1; 229 230 authsock_err: 231 free(auth_sock_name); 232 if (auth_sock_dir != NULL) { 233 rmdir(auth_sock_dir); 234 free(auth_sock_dir); 235 } 236 if (sock != -1) 237 close(sock); 238 auth_sock_name = NULL; 239 auth_sock_dir = NULL; 240 return 0; 241 } 242 243 static void 244 display_loginmsg(void) 245 { 246 if (buffer_len(&loginmsg) > 0) { 247 buffer_append(&loginmsg, "\0", 1); 248 printf("%s", (char *)buffer_ptr(&loginmsg)); 249 buffer_clear(&loginmsg); 250 } 251 } 252 253 void 254 do_authenticated(Authctxt *authctxt) 255 { 256 setproctitle("%s", authctxt->pw->pw_name); 257 258 /* setup the channel layer */ 259 /* XXX - streamlocal? */ 260 if (no_port_forwarding_flag || 261 (options.allow_tcp_forwarding & FORWARD_LOCAL) == 0) 262 channel_disable_adm_local_opens(); 263 else 264 channel_permit_all_opens(); 265 266 auth_debug_send(); 267 268 if (compat20) 269 do_authenticated2(authctxt); 270 else 271 do_authenticated1(authctxt); 272 273 do_cleanup(authctxt); 274 } 275 276 /* 277 * Prepares for an interactive session. This is called after the user has 278 * been successfully authenticated. During this message exchange, pseudo 279 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings 280 * are requested, etc. 281 */ 282 static void 283 do_authenticated1(Authctxt *authctxt) 284 { 285 Session *s; 286 char *command; 287 int success, type, screen_flag; 288 int enable_compression_after_reply = 0; 289 u_int proto_len, data_len, dlen, compression_level = 0; 290 291 s = session_new(); 292 if (s == NULL) { 293 error("no more sessions"); 294 return; 295 } 296 s->authctxt = authctxt; 297 s->pw = authctxt->pw; 298 299 /* 300 * We stay in this loop until the client requests to execute a shell 301 * or a command. 302 */ 303 for (;;) { 304 success = 0; 305 306 /* Get a packet from the client. */ 307 type = packet_read(); 308 309 /* Process the packet. */ 310 switch (type) { 311 case SSH_CMSG_REQUEST_COMPRESSION: 312 compression_level = packet_get_int(); 313 packet_check_eom(); 314 if (compression_level < 1 || compression_level > 9) { 315 packet_send_debug("Received invalid compression level %d.", 316 compression_level); 317 break; 318 } 319 if (options.compression == COMP_NONE) { 320 debug2("compression disabled"); 321 break; 322 } 323 /* Enable compression after we have responded with SUCCESS. */ 324 enable_compression_after_reply = 1; 325 success = 1; 326 break; 327 328 case SSH_CMSG_REQUEST_PTY: 329 success = session_pty_req(s); 330 break; 331 332 case SSH_CMSG_X11_REQUEST_FORWARDING: 333 s->auth_proto = packet_get_string(&proto_len); 334 s->auth_data = packet_get_string(&data_len); 335 336 screen_flag = packet_get_protocol_flags() & 337 SSH_PROTOFLAG_SCREEN_NUMBER; 338 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag); 339 340 if (packet_remaining() == 4) { 341 if (!screen_flag) 342 debug2("Buggy client: " 343 "X11 screen flag missing"); 344 s->screen = packet_get_int(); 345 } else { 346 s->screen = 0; 347 } 348 packet_check_eom(); 349 success = session_setup_x11fwd(s); 350 if (!success) { 351 free(s->auth_proto); 352 free(s->auth_data); 353 s->auth_proto = NULL; 354 s->auth_data = NULL; 355 } 356 break; 357 358 case SSH_CMSG_AGENT_REQUEST_FORWARDING: 359 if (!options.allow_agent_forwarding || 360 no_agent_forwarding_flag || compat13) { 361 debug("Authentication agent forwarding not permitted for this authentication."); 362 break; 363 } 364 debug("Received authentication agent forwarding request."); 365 success = auth_input_request_forwarding(s->pw); 366 break; 367 368 case SSH_CMSG_PORT_FORWARD_REQUEST: 369 if (no_port_forwarding_flag) { 370 debug("Port forwarding not permitted for this authentication."); 371 break; 372 } 373 if (!(options.allow_tcp_forwarding & FORWARD_REMOTE)) { 374 debug("Port forwarding not permitted."); 375 break; 376 } 377 debug("Received TCP/IP port forwarding request."); 378 if (channel_input_port_forward_request(s->pw->pw_uid == 0, 379 &options.fwd_opts) < 0) { 380 debug("Port forwarding failed."); 381 break; 382 } 383 success = 1; 384 break; 385 386 case SSH_CMSG_MAX_PACKET_SIZE: 387 if (packet_set_maxsize(packet_get_int()) > 0) 388 success = 1; 389 break; 390 391 case SSH_CMSG_EXEC_SHELL: 392 case SSH_CMSG_EXEC_CMD: 393 if (type == SSH_CMSG_EXEC_CMD) { 394 command = packet_get_string(&dlen); 395 debug("Exec command '%.500s'", command); 396 if (do_exec(s, command) != 0) 397 packet_disconnect( 398 "command execution failed"); 399 free(command); 400 } else { 401 if (do_exec(s, NULL) != 0) 402 packet_disconnect( 403 "shell execution failed"); 404 } 405 packet_check_eom(); 406 session_close(s); 407 return; 408 409 default: 410 /* 411 * Any unknown messages in this phase are ignored, 412 * and a failure message is returned. 413 */ 414 logit("Unknown packet type received after authentication: %d", type); 415 } 416 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE); 417 packet_send(); 418 packet_write_wait(); 419 420 /* Enable compression now that we have replied if appropriate. */ 421 if (enable_compression_after_reply) { 422 enable_compression_after_reply = 0; 423 packet_start_compression(compression_level); 424 } 425 } 426 } 427 428 #define USE_PIPES 1 429 /* 430 * This is called to fork and execute a command when we have no tty. This 431 * will call do_child from the child, and server_loop from the parent after 432 * setting up file descriptors and such. 433 */ 434 int 435 do_exec_no_pty(Session *s, const char *command) 436 { 437 pid_t pid; 438 439 #ifdef USE_PIPES 440 int pin[2], pout[2], perr[2]; 441 442 if (s == NULL) 443 fatal("do_exec_no_pty: no session"); 444 445 /* Allocate pipes for communicating with the program. */ 446 if (pipe(pin) < 0) { 447 error("%s: pipe in: %.100s", __func__, strerror(errno)); 448 return -1; 449 } 450 if (pipe(pout) < 0) { 451 error("%s: pipe out: %.100s", __func__, strerror(errno)); 452 close(pin[0]); 453 close(pin[1]); 454 return -1; 455 } 456 if (pipe(perr) < 0) { 457 error("%s: pipe err: %.100s", __func__, 458 strerror(errno)); 459 close(pin[0]); 460 close(pin[1]); 461 close(pout[0]); 462 close(pout[1]); 463 return -1; 464 } 465 #else 466 int inout[2], err[2]; 467 468 if (s == NULL) 469 fatal("do_exec_no_pty: no session"); 470 471 /* Uses socket pairs to communicate with the program. */ 472 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) { 473 error("%s: socketpair #1: %.100s", __func__, strerror(errno)); 474 return -1; 475 } 476 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) { 477 error("%s: socketpair #2: %.100s", __func__, 478 strerror(errno)); 479 close(inout[0]); 480 close(inout[1]); 481 return -1; 482 } 483 #endif 484 485 session_proctitle(s); 486 487 /* Fork the child. */ 488 switch ((pid = fork())) { 489 case -1: 490 error("%s: fork: %.100s", __func__, strerror(errno)); 491 #ifdef USE_PIPES 492 close(pin[0]); 493 close(pin[1]); 494 close(pout[0]); 495 close(pout[1]); 496 close(perr[0]); 497 close(perr[1]); 498 #else 499 close(inout[0]); 500 close(inout[1]); 501 close(err[0]); 502 close(err[1]); 503 #endif 504 return -1; 505 case 0: 506 is_child = 1; 507 508 /* Child. Reinitialize the log since the pid has changed. */ 509 log_init(__progname, options.log_level, 510 options.log_facility, log_stderr); 511 512 /* 513 * Create a new session and process group since the 4.4BSD 514 * setlogin() affects the entire process group. 515 */ 516 if (setsid() < 0) 517 error("setsid failed: %.100s", strerror(errno)); 518 519 #ifdef USE_PIPES 520 /* 521 * Redirect stdin. We close the parent side of the socket 522 * pair, and make the child side the standard input. 523 */ 524 close(pin[1]); 525 if (dup2(pin[0], 0) < 0) 526 perror("dup2 stdin"); 527 close(pin[0]); 528 529 /* Redirect stdout. */ 530 close(pout[0]); 531 if (dup2(pout[1], 1) < 0) 532 perror("dup2 stdout"); 533 close(pout[1]); 534 535 /* Redirect stderr. */ 536 close(perr[0]); 537 if (dup2(perr[1], 2) < 0) 538 perror("dup2 stderr"); 539 close(perr[1]); 540 #else 541 /* 542 * Redirect stdin, stdout, and stderr. Stdin and stdout will 543 * use the same socket, as some programs (particularly rdist) 544 * seem to depend on it. 545 */ 546 close(inout[1]); 547 close(err[1]); 548 if (dup2(inout[0], 0) < 0) /* stdin */ 549 perror("dup2 stdin"); 550 if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */ 551 perror("dup2 stdout"); 552 close(inout[0]); 553 if (dup2(err[0], 2) < 0) /* stderr */ 554 perror("dup2 stderr"); 555 close(err[0]); 556 #endif 557 558 559 #ifdef _UNICOS 560 cray_init_job(s->pw); /* set up cray jid and tmpdir */ 561 #endif 562 563 /* Do processing for the child (exec command etc). */ 564 do_child(s, command); 565 /* NOTREACHED */ 566 default: 567 break; 568 } 569 570 #ifdef _UNICOS 571 signal(WJSIGNAL, cray_job_termination_handler); 572 #endif /* _UNICOS */ 573 #ifdef HAVE_CYGWIN 574 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE); 575 #endif 576 577 s->pid = pid; 578 /* Set interactive/non-interactive mode. */ 579 packet_set_interactive(s->display != NULL, 580 options.ip_qos_interactive, options.ip_qos_bulk); 581 582 /* 583 * Clear loginmsg, since it's the child's responsibility to display 584 * it to the user, otherwise multiple sessions may accumulate 585 * multiple copies of the login messages. 586 */ 587 buffer_clear(&loginmsg); 588 589 #ifdef USE_PIPES 590 /* We are the parent. Close the child sides of the pipes. */ 591 close(pin[0]); 592 close(pout[1]); 593 close(perr[1]); 594 595 if (compat20) { 596 session_set_fds(s, pin[1], pout[0], perr[0], 597 s->is_subsystem, 0); 598 } else { 599 /* Enter the interactive session. */ 600 server_loop(pid, pin[1], pout[0], perr[0]); 601 /* server_loop has closed pin[1], pout[0], and perr[0]. */ 602 } 603 #else 604 /* We are the parent. Close the child sides of the socket pairs. */ 605 close(inout[0]); 606 close(err[0]); 607 608 /* 609 * Enter the interactive session. Note: server_loop must be able to 610 * handle the case that fdin and fdout are the same. 611 */ 612 if (compat20) { 613 session_set_fds(s, inout[1], inout[1], err[1], 614 s->is_subsystem, 0); 615 } else { 616 server_loop(pid, inout[1], inout[1], err[1]); 617 /* server_loop has closed inout[1] and err[1]. */ 618 } 619 #endif 620 return 0; 621 } 622 623 /* 624 * This is called to fork and execute a command when we have a tty. This 625 * will call do_child from the child, and server_loop from the parent after 626 * setting up file descriptors, controlling tty, updating wtmp, utmp, 627 * lastlog, and other such operations. 628 */ 629 int 630 do_exec_pty(Session *s, const char *command) 631 { 632 int fdout, ptyfd, ttyfd, ptymaster; 633 pid_t pid; 634 635 if (s == NULL) 636 fatal("do_exec_pty: no session"); 637 ptyfd = s->ptyfd; 638 ttyfd = s->ttyfd; 639 640 /* 641 * Create another descriptor of the pty master side for use as the 642 * standard input. We could use the original descriptor, but this 643 * simplifies code in server_loop. The descriptor is bidirectional. 644 * Do this before forking (and cleanup in the child) so as to 645 * detect and gracefully fail out-of-fd conditions. 646 */ 647 if ((fdout = dup(ptyfd)) < 0) { 648 error("%s: dup #1: %s", __func__, strerror(errno)); 649 close(ttyfd); 650 close(ptyfd); 651 return -1; 652 } 653 /* we keep a reference to the pty master */ 654 if ((ptymaster = dup(ptyfd)) < 0) { 655 error("%s: dup #2: %s", __func__, strerror(errno)); 656 close(ttyfd); 657 close(ptyfd); 658 close(fdout); 659 return -1; 660 } 661 662 /* Fork the child. */ 663 switch ((pid = fork())) { 664 case -1: 665 error("%s: fork: %.100s", __func__, strerror(errno)); 666 close(fdout); 667 close(ptymaster); 668 close(ttyfd); 669 close(ptyfd); 670 return -1; 671 case 0: 672 is_child = 1; 673 674 close(fdout); 675 close(ptymaster); 676 677 /* Child. Reinitialize the log because the pid has changed. */ 678 log_init(__progname, options.log_level, 679 options.log_facility, log_stderr); 680 /* Close the master side of the pseudo tty. */ 681 close(ptyfd); 682 683 /* Make the pseudo tty our controlling tty. */ 684 pty_make_controlling_tty(&ttyfd, s->tty); 685 686 /* Redirect stdin/stdout/stderr from the pseudo tty. */ 687 if (dup2(ttyfd, 0) < 0) 688 error("dup2 stdin: %s", strerror(errno)); 689 if (dup2(ttyfd, 1) < 0) 690 error("dup2 stdout: %s", strerror(errno)); 691 if (dup2(ttyfd, 2) < 0) 692 error("dup2 stderr: %s", strerror(errno)); 693 694 /* Close the extra descriptor for the pseudo tty. */ 695 close(ttyfd); 696 697 /* record login, etc. similar to login(1) */ 698 #ifndef HAVE_OSF_SIA 699 if (!(options.use_login && command == NULL)) { 700 #ifdef _UNICOS 701 cray_init_job(s->pw); /* set up cray jid and tmpdir */ 702 #endif /* _UNICOS */ 703 do_login(s, command); 704 } 705 # ifdef LOGIN_NEEDS_UTMPX 706 else 707 do_pre_login(s); 708 # endif 709 #endif 710 /* 711 * Do common processing for the child, such as execing 712 * the command. 713 */ 714 do_child(s, command); 715 /* NOTREACHED */ 716 default: 717 break; 718 } 719 720 #ifdef _UNICOS 721 signal(WJSIGNAL, cray_job_termination_handler); 722 #endif /* _UNICOS */ 723 #ifdef HAVE_CYGWIN 724 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE); 725 #endif 726 727 s->pid = pid; 728 729 /* Parent. Close the slave side of the pseudo tty. */ 730 close(ttyfd); 731 732 /* Enter interactive session. */ 733 s->ptymaster = ptymaster; 734 packet_set_interactive(1, 735 options.ip_qos_interactive, options.ip_qos_bulk); 736 if (compat20) { 737 session_set_fds(s, ptyfd, fdout, -1, 1, 1); 738 } else { 739 server_loop(pid, ptyfd, fdout, -1); 740 /* server_loop _has_ closed ptyfd and fdout. */ 741 } 742 return 0; 743 } 744 745 #ifdef LOGIN_NEEDS_UTMPX 746 static void 747 do_pre_login(Session *s) 748 { 749 socklen_t fromlen; 750 struct sockaddr_storage from; 751 pid_t pid = getpid(); 752 753 /* 754 * Get IP address of client. If the connection is not a socket, let 755 * the address be 0.0.0.0. 756 */ 757 memset(&from, 0, sizeof(from)); 758 fromlen = sizeof(from); 759 if (packet_connection_is_on_socket()) { 760 if (getpeername(packet_get_connection_in(), 761 (struct sockaddr *)&from, &fromlen) < 0) { 762 debug("getpeername: %.100s", strerror(errno)); 763 cleanup_exit(255); 764 } 765 } 766 767 record_utmp_only(pid, s->tty, s->pw->pw_name, 768 get_remote_name_or_ip(utmp_len, options.use_dns), 769 (struct sockaddr *)&from, fromlen); 770 } 771 #endif 772 773 /* 774 * This is called to fork and execute a command. If another command is 775 * to be forced, execute that instead. 776 */ 777 int 778 do_exec(Session *s, const char *command) 779 { 780 int ret; 781 const char *forced = NULL; 782 char session_type[1024], *tty = NULL; 783 784 if (options.adm_forced_command) { 785 original_command = command; 786 command = options.adm_forced_command; 787 forced = "(config)"; 788 } else if (forced_command) { 789 original_command = command; 790 command = forced_command; 791 forced = "(key-option)"; 792 } 793 if (forced != NULL) { 794 if (IS_INTERNAL_SFTP(command)) { 795 s->is_subsystem = s->is_subsystem ? 796 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR; 797 } else if (s->is_subsystem) 798 s->is_subsystem = SUBSYSTEM_EXT; 799 snprintf(session_type, sizeof(session_type), 800 "forced-command %s '%.900s'", forced, command); 801 } else if (s->is_subsystem) { 802 snprintf(session_type, sizeof(session_type), 803 "subsystem '%.900s'", s->subsys); 804 } else if (command == NULL) { 805 snprintf(session_type, sizeof(session_type), "shell"); 806 } else { 807 /* NB. we don't log unforced commands to preserve privacy */ 808 snprintf(session_type, sizeof(session_type), "command"); 809 } 810 811 if (s->ttyfd != -1) { 812 tty = s->tty; 813 if (strncmp(tty, "/dev/", 5) == 0) 814 tty += 5; 815 } 816 817 verbose("Starting session: %s%s%s for %s from %.200s port %d", 818 session_type, 819 tty == NULL ? "" : " on ", 820 tty == NULL ? "" : tty, 821 s->pw->pw_name, 822 get_remote_ipaddr(), 823 get_remote_port()); 824 825 #ifdef SSH_AUDIT_EVENTS 826 if (command != NULL) 827 PRIVSEP(audit_run_command(command)); 828 else if (s->ttyfd == -1) { 829 char *shell = s->pw->pw_shell; 830 831 if (shell[0] == '\0') /* empty shell means /bin/sh */ 832 shell =_PATH_BSHELL; 833 PRIVSEP(audit_run_command(shell)); 834 } 835 #endif 836 if (s->ttyfd != -1) 837 ret = do_exec_pty(s, command); 838 else 839 ret = do_exec_no_pty(s, command); 840 841 original_command = NULL; 842 843 /* 844 * Clear loginmsg: it's the child's responsibility to display 845 * it to the user, otherwise multiple sessions may accumulate 846 * multiple copies of the login messages. 847 */ 848 buffer_clear(&loginmsg); 849 850 return ret; 851 } 852 853 /* administrative, login(1)-like work */ 854 void 855 do_login(Session *s, const char *command) 856 { 857 socklen_t fromlen; 858 struct sockaddr_storage from; 859 struct passwd * pw = s->pw; 860 pid_t pid = getpid(); 861 862 /* 863 * Get IP address of client. If the connection is not a socket, let 864 * the address be 0.0.0.0. 865 */ 866 memset(&from, 0, sizeof(from)); 867 fromlen = sizeof(from); 868 if (packet_connection_is_on_socket()) { 869 if (getpeername(packet_get_connection_in(), 870 (struct sockaddr *)&from, &fromlen) < 0) { 871 debug("getpeername: %.100s", strerror(errno)); 872 cleanup_exit(255); 873 } 874 } 875 876 /* Record that there was a login on that tty from the remote host. */ 877 if (!use_privsep) 878 record_login(pid, s->tty, pw->pw_name, pw->pw_uid, 879 get_remote_name_or_ip(utmp_len, 880 options.use_dns), 881 (struct sockaddr *)&from, fromlen); 882 883 #ifdef USE_PAM 884 /* 885 * If password change is needed, do it now. 886 * This needs to occur before the ~/.hushlogin check. 887 */ 888 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) { 889 display_loginmsg(); 890 do_pam_chauthtok(); 891 s->authctxt->force_pwchange = 0; 892 /* XXX - signal [net] parent to enable forwardings */ 893 } 894 #endif 895 896 if (check_quietlogin(s, command)) 897 return; 898 899 display_loginmsg(); 900 901 do_motd(); 902 } 903 904 /* 905 * Display the message of the day. 906 */ 907 void 908 do_motd(void) 909 { 910 FILE *f; 911 char buf[256]; 912 913 if (options.print_motd) { 914 #ifdef HAVE_LOGIN_CAP 915 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd", 916 "/etc/motd"), "r"); 917 #else 918 f = fopen("/etc/motd", "r"); 919 #endif 920 if (f) { 921 while (fgets(buf, sizeof(buf), f)) 922 fputs(buf, stdout); 923 fclose(f); 924 } 925 } 926 } 927 928 929 /* 930 * Check for quiet login, either .hushlogin or command given. 931 */ 932 int 933 check_quietlogin(Session *s, const char *command) 934 { 935 char buf[256]; 936 struct passwd *pw = s->pw; 937 struct stat st; 938 939 /* Return 1 if .hushlogin exists or a command given. */ 940 if (command != NULL) 941 return 1; 942 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir); 943 #ifdef HAVE_LOGIN_CAP 944 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0) 945 return 1; 946 #else 947 if (stat(buf, &st) >= 0) 948 return 1; 949 #endif 950 return 0; 951 } 952 953 /* 954 * Sets the value of the given variable in the environment. If the variable 955 * already exists, its value is overridden. 956 */ 957 void 958 child_set_env(char ***envp, u_int *envsizep, const char *name, 959 const char *value) 960 { 961 char **env; 962 u_int envsize; 963 u_int i, namelen; 964 965 if (strchr(name, '=') != NULL) { 966 error("Invalid environment variable \"%.100s\"", name); 967 return; 968 } 969 970 /* 971 * If we're passed an uninitialized list, allocate a single null 972 * entry before continuing. 973 */ 974 if (*envp == NULL && *envsizep == 0) { 975 *envp = xmalloc(sizeof(char *)); 976 *envp[0] = NULL; 977 *envsizep = 1; 978 } 979 980 /* 981 * Find the slot where the value should be stored. If the variable 982 * already exists, we reuse the slot; otherwise we append a new slot 983 * at the end of the array, expanding if necessary. 984 */ 985 env = *envp; 986 namelen = strlen(name); 987 for (i = 0; env[i]; i++) 988 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=') 989 break; 990 if (env[i]) { 991 /* Reuse the slot. */ 992 free(env[i]); 993 } else { 994 /* New variable. Expand if necessary. */ 995 envsize = *envsizep; 996 if (i >= envsize - 1) { 997 if (envsize >= 1000) 998 fatal("child_set_env: too many env vars"); 999 envsize += 50; 1000 env = (*envp) = xrealloc(env, envsize, sizeof(char *)); 1001 *envsizep = envsize; 1002 } 1003 /* Need to set the NULL pointer at end of array beyond the new slot. */ 1004 env[i + 1] = NULL; 1005 } 1006 1007 /* Allocate space and format the variable in the appropriate slot. */ 1008 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1); 1009 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value); 1010 } 1011 1012 /* 1013 * Reads environment variables from the given file and adds/overrides them 1014 * into the environment. If the file does not exist, this does nothing. 1015 * Otherwise, it must consist of empty lines, comments (line starts with '#') 1016 * and assignments of the form name=value. No other forms are allowed. 1017 */ 1018 static void 1019 read_environment_file(char ***env, u_int *envsize, 1020 const char *filename) 1021 { 1022 FILE *f; 1023 char buf[4096]; 1024 char *cp, *value; 1025 u_int lineno = 0; 1026 1027 f = fopen(filename, "r"); 1028 if (!f) 1029 return; 1030 1031 while (fgets(buf, sizeof(buf), f)) { 1032 if (++lineno > 1000) 1033 fatal("Too many lines in environment file %s", filename); 1034 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++) 1035 ; 1036 if (!*cp || *cp == '#' || *cp == '\n') 1037 continue; 1038 1039 cp[strcspn(cp, "\n")] = '\0'; 1040 1041 value = strchr(cp, '='); 1042 if (value == NULL) { 1043 fprintf(stderr, "Bad line %u in %.100s\n", lineno, 1044 filename); 1045 continue; 1046 } 1047 /* 1048 * Replace the equals sign by nul, and advance value to 1049 * the value string. 1050 */ 1051 *value = '\0'; 1052 value++; 1053 child_set_env(env, envsize, cp, value); 1054 } 1055 fclose(f); 1056 } 1057 1058 #ifdef HAVE_ETC_DEFAULT_LOGIN 1059 /* 1060 * Return named variable from specified environment, or NULL if not present. 1061 */ 1062 static char * 1063 child_get_env(char **env, const char *name) 1064 { 1065 int i; 1066 size_t len; 1067 1068 len = strlen(name); 1069 for (i=0; env[i] != NULL; i++) 1070 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=') 1071 return(env[i] + len + 1); 1072 return NULL; 1073 } 1074 1075 /* 1076 * Read /etc/default/login. 1077 * We pick up the PATH (or SUPATH for root) and UMASK. 1078 */ 1079 static void 1080 read_etc_default_login(char ***env, u_int *envsize, uid_t uid) 1081 { 1082 char **tmpenv = NULL, *var; 1083 u_int i, tmpenvsize = 0; 1084 u_long mask; 1085 1086 /* 1087 * We don't want to copy the whole file to the child's environment, 1088 * so we use a temporary environment and copy the variables we're 1089 * interested in. 1090 */ 1091 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login"); 1092 1093 if (tmpenv == NULL) 1094 return; 1095 1096 if (uid == 0) 1097 var = child_get_env(tmpenv, "SUPATH"); 1098 else 1099 var = child_get_env(tmpenv, "PATH"); 1100 if (var != NULL) 1101 child_set_env(env, envsize, "PATH", var); 1102 1103 if ((var = child_get_env(tmpenv, "UMASK")) != NULL) 1104 if (sscanf(var, "%5lo", &mask) == 1) 1105 umask((mode_t)mask); 1106 1107 for (i = 0; tmpenv[i] != NULL; i++) 1108 free(tmpenv[i]); 1109 free(tmpenv); 1110 } 1111 #endif /* HAVE_ETC_DEFAULT_LOGIN */ 1112 1113 void 1114 copy_environment(char **source, char ***env, u_int *envsize) 1115 { 1116 char *var_name, *var_val; 1117 int i; 1118 1119 if (source == NULL) 1120 return; 1121 1122 for(i = 0; source[i] != NULL; i++) { 1123 var_name = xstrdup(source[i]); 1124 if ((var_val = strstr(var_name, "=")) == NULL) { 1125 free(var_name); 1126 continue; 1127 } 1128 *var_val++ = '\0'; 1129 1130 debug3("Copy environment: %s=%s", var_name, var_val); 1131 child_set_env(env, envsize, var_name, var_val); 1132 1133 free(var_name); 1134 } 1135 } 1136 1137 static char ** 1138 do_setup_env(Session *s, const char *shell) 1139 { 1140 char buf[256]; 1141 u_int i, envsize; 1142 char **env, *laddr; 1143 struct passwd *pw = s->pw; 1144 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN) 1145 char *path = NULL; 1146 #else 1147 extern char **environ; 1148 char **senv, **var; 1149 #endif 1150 1151 /* Initialize the environment. */ 1152 envsize = 100; 1153 env = xcalloc(envsize, sizeof(char *)); 1154 env[0] = NULL; 1155 1156 #ifdef HAVE_CYGWIN 1157 /* 1158 * The Windows environment contains some setting which are 1159 * important for a running system. They must not be dropped. 1160 */ 1161 { 1162 char **p; 1163 1164 p = fetch_windows_environment(); 1165 copy_environment(p, &env, &envsize); 1166 free_windows_environment(p); 1167 } 1168 #endif 1169 1170 if (getenv("TZ")) 1171 child_set_env(&env, &envsize, "TZ", getenv("TZ")); 1172 1173 #ifdef GSSAPI 1174 /* Allow any GSSAPI methods that we've used to alter 1175 * the childs environment as they see fit 1176 */ 1177 ssh_gssapi_do_child(&env, &envsize); 1178 #endif 1179 1180 if (!options.use_login) { 1181 /* Set basic environment. */ 1182 for (i = 0; i < s->num_env; i++) 1183 child_set_env(&env, &envsize, s->env[i].name, 1184 s->env[i].val); 1185 1186 child_set_env(&env, &envsize, "USER", pw->pw_name); 1187 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name); 1188 #ifdef _AIX 1189 child_set_env(&env, &envsize, "LOGIN", pw->pw_name); 1190 #endif 1191 child_set_env(&env, &envsize, "HOME", pw->pw_dir); 1192 snprintf(buf, sizeof buf, "%.200s/%.50s", 1193 _PATH_MAILDIR, pw->pw_name); 1194 child_set_env(&env, &envsize, "MAIL", buf); 1195 #ifdef HAVE_LOGIN_CAP 1196 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH); 1197 child_set_env(&env, &envsize, "TERM", "su"); 1198 senv = environ; 1199 environ = xmalloc(sizeof(char *)); 1200 *environ = NULL; 1201 (void) setusercontext(lc, pw, pw->pw_uid, 1202 LOGIN_SETENV|LOGIN_SETPATH); 1203 copy_environment(environ, &env, &envsize); 1204 for (var = environ; *var != NULL; ++var) 1205 free(*var); 1206 free(environ); 1207 environ = senv; 1208 #else /* HAVE_LOGIN_CAP */ 1209 # ifndef HAVE_CYGWIN 1210 /* 1211 * There's no standard path on Windows. The path contains 1212 * important components pointing to the system directories, 1213 * needed for loading shared libraries. So the path better 1214 * remains intact here. 1215 */ 1216 # ifdef HAVE_ETC_DEFAULT_LOGIN 1217 read_etc_default_login(&env, &envsize, pw->pw_uid); 1218 path = child_get_env(env, "PATH"); 1219 # endif /* HAVE_ETC_DEFAULT_LOGIN */ 1220 if (path == NULL || *path == '\0') { 1221 child_set_env(&env, &envsize, "PATH", 1222 s->pw->pw_uid == 0 ? 1223 SUPERUSER_PATH : _PATH_STDPATH); 1224 } 1225 # endif /* HAVE_CYGWIN */ 1226 #endif /* HAVE_LOGIN_CAP */ 1227 1228 /* Normal systems set SHELL by default. */ 1229 child_set_env(&env, &envsize, "SHELL", shell); 1230 } 1231 1232 /* Set custom environment options from RSA authentication. */ 1233 if (!options.use_login) { 1234 while (custom_environment) { 1235 struct envstring *ce = custom_environment; 1236 char *str = ce->s; 1237 1238 for (i = 0; str[i] != '=' && str[i]; i++) 1239 ; 1240 if (str[i] == '=') { 1241 str[i] = 0; 1242 child_set_env(&env, &envsize, str, str + i + 1); 1243 } 1244 custom_environment = ce->next; 1245 free(ce->s); 1246 free(ce); 1247 } 1248 } 1249 1250 /* SSH_CLIENT deprecated */ 1251 snprintf(buf, sizeof buf, "%.50s %d %d", 1252 get_remote_ipaddr(), get_remote_port(), get_local_port()); 1253 child_set_env(&env, &envsize, "SSH_CLIENT", buf); 1254 1255 laddr = get_local_ipaddr(packet_get_connection_in()); 1256 snprintf(buf, sizeof buf, "%.50s %d %.50s %d", 1257 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port()); 1258 free(laddr); 1259 child_set_env(&env, &envsize, "SSH_CONNECTION", buf); 1260 1261 if (s->ttyfd != -1) 1262 child_set_env(&env, &envsize, "SSH_TTY", s->tty); 1263 if (s->term) 1264 child_set_env(&env, &envsize, "TERM", s->term); 1265 if (s->display) 1266 child_set_env(&env, &envsize, "DISPLAY", s->display); 1267 if (original_command) 1268 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND", 1269 original_command); 1270 1271 #ifdef _UNICOS 1272 if (cray_tmpdir[0] != '\0') 1273 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir); 1274 #endif /* _UNICOS */ 1275 1276 /* 1277 * Since we clear KRB5CCNAME at startup, if it's set now then it 1278 * must have been set by a native authentication method (eg AIX or 1279 * SIA), so copy it to the child. 1280 */ 1281 { 1282 char *cp; 1283 1284 if ((cp = getenv("KRB5CCNAME")) != NULL) 1285 child_set_env(&env, &envsize, "KRB5CCNAME", cp); 1286 } 1287 1288 #ifdef _AIX 1289 { 1290 char *cp; 1291 1292 if ((cp = getenv("AUTHSTATE")) != NULL) 1293 child_set_env(&env, &envsize, "AUTHSTATE", cp); 1294 read_environment_file(&env, &envsize, "/etc/environment"); 1295 } 1296 #endif 1297 #ifdef KRB5 1298 if (s->authctxt->krb5_ccname) 1299 child_set_env(&env, &envsize, "KRB5CCNAME", 1300 s->authctxt->krb5_ccname); 1301 #endif 1302 #ifdef USE_PAM 1303 /* 1304 * Pull in any environment variables that may have 1305 * been set by PAM. 1306 */ 1307 if (options.use_pam) { 1308 char **p; 1309 1310 p = fetch_pam_child_environment(); 1311 copy_environment(p, &env, &envsize); 1312 free_pam_environment(p); 1313 1314 p = fetch_pam_environment(); 1315 copy_environment(p, &env, &envsize); 1316 free_pam_environment(p); 1317 } 1318 #endif /* USE_PAM */ 1319 1320 if (auth_sock_name != NULL) 1321 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME, 1322 auth_sock_name); 1323 1324 /* read $HOME/.ssh/environment. */ 1325 if (options.permit_user_env && !options.use_login) { 1326 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", 1327 strcmp(pw->pw_dir, "/") ? pw->pw_dir : ""); 1328 read_environment_file(&env, &envsize, buf); 1329 } 1330 if (debug_flag) { 1331 /* dump the environment */ 1332 fprintf(stderr, "Environment:\n"); 1333 for (i = 0; env[i]; i++) 1334 fprintf(stderr, " %.200s\n", env[i]); 1335 } 1336 return env; 1337 } 1338 1339 /* 1340 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found 1341 * first in this order). 1342 */ 1343 static void 1344 do_rc_files(Session *s, const char *shell) 1345 { 1346 FILE *f = NULL; 1347 char cmd[1024]; 1348 int do_xauth; 1349 struct stat st; 1350 1351 do_xauth = 1352 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL; 1353 1354 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */ 1355 if (!s->is_subsystem && options.adm_forced_command == NULL && 1356 !no_user_rc && options.permit_user_rc && 1357 stat(_PATH_SSH_USER_RC, &st) >= 0) { 1358 snprintf(cmd, sizeof cmd, "%s -c '%s %s'", 1359 shell, _PATH_BSHELL, _PATH_SSH_USER_RC); 1360 if (debug_flag) 1361 fprintf(stderr, "Running %s\n", cmd); 1362 f = popen(cmd, "w"); 1363 if (f) { 1364 if (do_xauth) 1365 fprintf(f, "%s %s\n", s->auth_proto, 1366 s->auth_data); 1367 pclose(f); 1368 } else 1369 fprintf(stderr, "Could not run %s\n", 1370 _PATH_SSH_USER_RC); 1371 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) { 1372 if (debug_flag) 1373 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL, 1374 _PATH_SSH_SYSTEM_RC); 1375 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w"); 1376 if (f) { 1377 if (do_xauth) 1378 fprintf(f, "%s %s\n", s->auth_proto, 1379 s->auth_data); 1380 pclose(f); 1381 } else 1382 fprintf(stderr, "Could not run %s\n", 1383 _PATH_SSH_SYSTEM_RC); 1384 } else if (do_xauth && options.xauth_location != NULL) { 1385 /* Add authority data to .Xauthority if appropriate. */ 1386 if (debug_flag) { 1387 fprintf(stderr, 1388 "Running %.500s remove %.100s\n", 1389 options.xauth_location, s->auth_display); 1390 fprintf(stderr, 1391 "%.500s add %.100s %.100s %.100s\n", 1392 options.xauth_location, s->auth_display, 1393 s->auth_proto, s->auth_data); 1394 } 1395 snprintf(cmd, sizeof cmd, "%s -q -", 1396 options.xauth_location); 1397 f = popen(cmd, "w"); 1398 if (f) { 1399 fprintf(f, "remove %s\n", 1400 s->auth_display); 1401 fprintf(f, "add %s %s %s\n", 1402 s->auth_display, s->auth_proto, 1403 s->auth_data); 1404 pclose(f); 1405 } else { 1406 fprintf(stderr, "Could not run %s\n", 1407 cmd); 1408 } 1409 } 1410 } 1411 1412 static void 1413 do_nologin(struct passwd *pw) 1414 { 1415 FILE *f = NULL; 1416 char buf[1024], *nl, *def_nl = _PATH_NOLOGIN; 1417 struct stat sb; 1418 1419 #ifdef HAVE_LOGIN_CAP 1420 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0) 1421 return; 1422 nl = login_getcapstr(lc, "nologin", def_nl, def_nl); 1423 #else 1424 if (pw->pw_uid == 0) 1425 return; 1426 nl = def_nl; 1427 #endif 1428 if (stat(nl, &sb) == -1) { 1429 if (nl != def_nl) 1430 free(nl); 1431 return; 1432 } 1433 1434 /* /etc/nologin exists. Print its contents if we can and exit. */ 1435 logit("User %.100s not allowed because %s exists", pw->pw_name, nl); 1436 if ((f = fopen(nl, "r")) != NULL) { 1437 while (fgets(buf, sizeof(buf), f)) 1438 fputs(buf, stderr); 1439 fclose(f); 1440 } 1441 exit(254); 1442 } 1443 1444 /* 1445 * Chroot into a directory after checking it for safety: all path components 1446 * must be root-owned directories with strict permissions. 1447 */ 1448 static void 1449 safely_chroot(const char *path, uid_t uid) 1450 { 1451 const char *cp; 1452 char component[MAXPATHLEN]; 1453 struct stat st; 1454 1455 if (*path != '/') 1456 fatal("chroot path does not begin at root"); 1457 if (strlen(path) >= sizeof(component)) 1458 fatal("chroot path too long"); 1459 1460 /* 1461 * Descend the path, checking that each component is a 1462 * root-owned directory with strict permissions. 1463 */ 1464 for (cp = path; cp != NULL;) { 1465 if ((cp = strchr(cp, '/')) == NULL) 1466 strlcpy(component, path, sizeof(component)); 1467 else { 1468 cp++; 1469 memcpy(component, path, cp - path); 1470 component[cp - path] = '\0'; 1471 } 1472 1473 debug3("%s: checking '%s'", __func__, component); 1474 1475 if (stat(component, &st) != 0) 1476 fatal("%s: stat(\"%s\"): %s", __func__, 1477 component, strerror(errno)); 1478 if (st.st_uid != 0 || (st.st_mode & 022) != 0) 1479 fatal("bad ownership or modes for chroot " 1480 "directory %s\"%s\"", 1481 cp == NULL ? "" : "component ", component); 1482 if (!S_ISDIR(st.st_mode)) 1483 fatal("chroot path %s\"%s\" is not a directory", 1484 cp == NULL ? "" : "component ", component); 1485 1486 } 1487 1488 if (chdir(path) == -1) 1489 fatal("Unable to chdir to chroot path \"%s\": " 1490 "%s", path, strerror(errno)); 1491 if (chroot(path) == -1) 1492 fatal("chroot(\"%s\"): %s", path, strerror(errno)); 1493 if (chdir("/") == -1) 1494 fatal("%s: chdir(/) after chroot: %s", 1495 __func__, strerror(errno)); 1496 verbose("Changed root directory to \"%s\"", path); 1497 } 1498 1499 /* Set login name, uid, gid, and groups. */ 1500 void 1501 do_setusercontext(struct passwd *pw) 1502 { 1503 char *chroot_path, *tmp; 1504 #ifdef USE_LIBIAF 1505 int doing_chroot = 0; 1506 #endif 1507 1508 platform_setusercontext(pw); 1509 1510 if (platform_privileged_uidswap()) { 1511 #ifdef HAVE_LOGIN_CAP 1512 if (setusercontext(lc, pw, pw->pw_uid, 1513 (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH|LOGIN_SETUSER))) < 0) { 1514 perror("unable to set user context"); 1515 exit(1); 1516 } 1517 #else 1518 if (setlogin(pw->pw_name) < 0) 1519 error("setlogin failed: %s", strerror(errno)); 1520 if (setgid(pw->pw_gid) < 0) { 1521 perror("setgid"); 1522 exit(1); 1523 } 1524 /* Initialize the group list. */ 1525 if (initgroups(pw->pw_name, pw->pw_gid) < 0) { 1526 perror("initgroups"); 1527 exit(1); 1528 } 1529 endgrent(); 1530 #endif 1531 1532 platform_setusercontext_post_groups(pw); 1533 1534 if (options.chroot_directory != NULL && 1535 strcasecmp(options.chroot_directory, "none") != 0) { 1536 tmp = tilde_expand_filename(options.chroot_directory, 1537 pw->pw_uid); 1538 chroot_path = percent_expand(tmp, "h", pw->pw_dir, 1539 "u", pw->pw_name, (char *)NULL); 1540 safely_chroot(chroot_path, pw->pw_uid); 1541 free(tmp); 1542 free(chroot_path); 1543 /* Make sure we don't attempt to chroot again */ 1544 free(options.chroot_directory); 1545 options.chroot_directory = NULL; 1546 #ifdef USE_LIBIAF 1547 doing_chroot = 1; 1548 #endif 1549 } 1550 1551 #ifdef HAVE_LOGIN_CAP 1552 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) { 1553 perror("unable to set user context (setuser)"); 1554 exit(1); 1555 } 1556 /* 1557 * FreeBSD's setusercontext() will not apply the user's 1558 * own umask setting unless running with the user's UID. 1559 */ 1560 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK); 1561 #else 1562 # ifdef USE_LIBIAF 1563 /* In a chroot environment, the set_id() will always fail; typically 1564 * because of the lack of necessary authentication services and runtime 1565 * such as ./usr/lib/libiaf.so, ./usr/lib/libpam.so.1, and ./etc/passwd 1566 * We skip it in the internal sftp chroot case. 1567 * We'll lose auditing and ACLs but permanently_set_uid will 1568 * take care of the rest. 1569 */ 1570 if ((doing_chroot == 0) && set_id(pw->pw_name) != 0) { 1571 fatal("set_id(%s) Failed", pw->pw_name); 1572 } 1573 # endif /* USE_LIBIAF */ 1574 /* Permanently switch to the desired uid. */ 1575 permanently_set_uid(pw); 1576 #endif 1577 } else if (options.chroot_directory != NULL && 1578 strcasecmp(options.chroot_directory, "none") != 0) { 1579 fatal("server lacks privileges to chroot to ChrootDirectory"); 1580 } 1581 1582 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid) 1583 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid); 1584 } 1585 1586 static void 1587 do_pwchange(Session *s) 1588 { 1589 fflush(NULL); 1590 fprintf(stderr, "WARNING: Your password has expired.\n"); 1591 if (s->ttyfd != -1) { 1592 fprintf(stderr, 1593 "You must change your password now and login again!\n"); 1594 #ifdef WITH_SELINUX 1595 setexeccon(NULL); 1596 #endif 1597 #ifdef PASSWD_NEEDS_USERNAME 1598 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name, 1599 (char *)NULL); 1600 #else 1601 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL); 1602 #endif 1603 perror("passwd"); 1604 } else { 1605 fprintf(stderr, 1606 "Password change required but no TTY available.\n"); 1607 } 1608 exit(1); 1609 } 1610 1611 static void 1612 launch_login(struct passwd *pw, const char *hostname) 1613 { 1614 /* Launch login(1). */ 1615 1616 execl(LOGIN_PROGRAM, "login", "-h", hostname, 1617 #ifdef xxxLOGIN_NEEDS_TERM 1618 (s->term ? s->term : "unknown"), 1619 #endif /* LOGIN_NEEDS_TERM */ 1620 #ifdef LOGIN_NO_ENDOPT 1621 "-p", "-f", pw->pw_name, (char *)NULL); 1622 #else 1623 "-p", "-f", "--", pw->pw_name, (char *)NULL); 1624 #endif 1625 1626 /* Login couldn't be executed, die. */ 1627 1628 perror("login"); 1629 exit(1); 1630 } 1631 1632 static void 1633 child_close_fds(void) 1634 { 1635 extern AuthenticationConnection *auth_conn; 1636 1637 if (auth_conn) { 1638 ssh_close_authentication_connection(auth_conn); 1639 auth_conn = NULL; 1640 } 1641 1642 if (packet_get_connection_in() == packet_get_connection_out()) 1643 close(packet_get_connection_in()); 1644 else { 1645 close(packet_get_connection_in()); 1646 close(packet_get_connection_out()); 1647 } 1648 /* 1649 * Close all descriptors related to channels. They will still remain 1650 * open in the parent. 1651 */ 1652 /* XXX better use close-on-exec? -markus */ 1653 channel_close_all(); 1654 1655 /* 1656 * Close any extra file descriptors. Note that there may still be 1657 * descriptors left by system functions. They will be closed later. 1658 */ 1659 endpwent(); 1660 1661 /* 1662 * Close any extra open file descriptors so that we don't have them 1663 * hanging around in clients. Note that we want to do this after 1664 * initgroups, because at least on Solaris 2.3 it leaves file 1665 * descriptors open. 1666 */ 1667 closefrom(STDERR_FILENO + 1); 1668 } 1669 1670 /* 1671 * Performs common processing for the child, such as setting up the 1672 * environment, closing extra file descriptors, setting the user and group 1673 * ids, and executing the command or shell. 1674 */ 1675 #define ARGV_MAX 10 1676 void 1677 do_child(Session *s, const char *command) 1678 { 1679 extern char **environ; 1680 char **env; 1681 char *argv[ARGV_MAX]; 1682 const char *shell, *shell0, *hostname = NULL; 1683 struct passwd *pw = s->pw; 1684 int r = 0; 1685 1686 /* remove hostkey from the child's memory */ 1687 destroy_sensitive_data(); 1688 1689 /* Force a password change */ 1690 if (s->authctxt->force_pwchange) { 1691 do_setusercontext(pw); 1692 child_close_fds(); 1693 do_pwchange(s); 1694 exit(1); 1695 } 1696 1697 /* login(1) is only called if we execute the login shell */ 1698 if (options.use_login && command != NULL) 1699 options.use_login = 0; 1700 1701 #ifdef _UNICOS 1702 cray_setup(pw->pw_uid, pw->pw_name, command); 1703 #endif /* _UNICOS */ 1704 1705 /* 1706 * Login(1) does this as well, and it needs uid 0 for the "-h" 1707 * switch, so we let login(1) to this for us. 1708 */ 1709 if (!options.use_login) { 1710 #ifdef HAVE_OSF_SIA 1711 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty); 1712 if (!check_quietlogin(s, command)) 1713 do_motd(); 1714 #else /* HAVE_OSF_SIA */ 1715 /* When PAM is enabled we rely on it to do the nologin check */ 1716 if (!options.use_pam) 1717 do_nologin(pw); 1718 do_setusercontext(pw); 1719 /* 1720 * PAM session modules in do_setusercontext may have 1721 * generated messages, so if this in an interactive 1722 * login then display them too. 1723 */ 1724 if (!check_quietlogin(s, command)) 1725 display_loginmsg(); 1726 #endif /* HAVE_OSF_SIA */ 1727 } 1728 1729 #ifdef USE_PAM 1730 if (options.use_pam && !options.use_login && !is_pam_session_open()) { 1731 debug3("PAM session not opened, exiting"); 1732 display_loginmsg(); 1733 exit(254); 1734 } 1735 #endif 1736 1737 /* 1738 * Get the shell from the password data. An empty shell field is 1739 * legal, and means /bin/sh. 1740 */ 1741 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell; 1742 1743 /* 1744 * Make sure $SHELL points to the shell from the password file, 1745 * even if shell is overridden from login.conf 1746 */ 1747 env = do_setup_env(s, shell); 1748 1749 #ifdef HAVE_LOGIN_CAP 1750 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell); 1751 #endif 1752 1753 /* we have to stash the hostname before we close our socket. */ 1754 if (options.use_login) 1755 hostname = get_remote_name_or_ip(utmp_len, 1756 options.use_dns); 1757 /* 1758 * Close the connection descriptors; note that this is the child, and 1759 * the server will still have the socket open, and it is important 1760 * that we do not shutdown it. Note that the descriptors cannot be 1761 * closed before building the environment, as we call 1762 * get_remote_ipaddr there. 1763 */ 1764 child_close_fds(); 1765 1766 /* 1767 * Must take new environment into use so that .ssh/rc, 1768 * /etc/ssh/sshrc and xauth are run in the proper environment. 1769 */ 1770 environ = env; 1771 1772 #if defined(KRB5) && defined(USE_AFS) 1773 /* 1774 * At this point, we check to see if AFS is active and if we have 1775 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see 1776 * if we can (and need to) extend the ticket into an AFS token. If 1777 * we don't do this, we run into potential problems if the user's 1778 * home directory is in AFS and it's not world-readable. 1779 */ 1780 1781 if (options.kerberos_get_afs_token && k_hasafs() && 1782 (s->authctxt->krb5_ctx != NULL)) { 1783 char cell[64]; 1784 1785 debug("Getting AFS token"); 1786 1787 k_setpag(); 1788 1789 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0) 1790 krb5_afslog(s->authctxt->krb5_ctx, 1791 s->authctxt->krb5_fwd_ccache, cell, NULL); 1792 1793 krb5_afslog_home(s->authctxt->krb5_ctx, 1794 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir); 1795 } 1796 #endif 1797 1798 /* Change current directory to the user's home directory. */ 1799 if (chdir(pw->pw_dir) < 0) { 1800 /* Suppress missing homedir warning for chroot case */ 1801 #ifdef HAVE_LOGIN_CAP 1802 r = login_getcapbool(lc, "requirehome", 0); 1803 #endif 1804 if (r || options.chroot_directory == NULL || 1805 strcasecmp(options.chroot_directory, "none") == 0) 1806 fprintf(stderr, "Could not chdir to home " 1807 "directory %s: %s\n", pw->pw_dir, 1808 strerror(errno)); 1809 if (r) 1810 exit(1); 1811 } 1812 1813 closefrom(STDERR_FILENO + 1); 1814 1815 if (!options.use_login) 1816 do_rc_files(s, shell); 1817 1818 /* restore SIGPIPE for child */ 1819 signal(SIGPIPE, SIG_DFL); 1820 1821 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) { 1822 printf("This service allows sftp connections only.\n"); 1823 fflush(NULL); 1824 exit(1); 1825 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) { 1826 extern int optind, optreset; 1827 int i; 1828 char *p, *args; 1829 1830 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME); 1831 args = xstrdup(command ? command : "sftp-server"); 1832 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " "))) 1833 if (i < ARGV_MAX - 1) 1834 argv[i++] = p; 1835 argv[i] = NULL; 1836 optind = optreset = 1; 1837 __progname = argv[0]; 1838 #ifdef WITH_SELINUX 1839 ssh_selinux_change_context("sftpd_t"); 1840 #endif 1841 exit(sftp_server_main(i, argv, s->pw)); 1842 } 1843 1844 fflush(NULL); 1845 1846 if (options.use_login) { 1847 launch_login(pw, hostname); 1848 /* NEVERREACHED */ 1849 } 1850 1851 /* Get the last component of the shell name. */ 1852 if ((shell0 = strrchr(shell, '/')) != NULL) 1853 shell0++; 1854 else 1855 shell0 = shell; 1856 1857 /* 1858 * If we have no command, execute the shell. In this case, the shell 1859 * name to be passed in argv[0] is preceded by '-' to indicate that 1860 * this is a login shell. 1861 */ 1862 if (!command) { 1863 char argv0[256]; 1864 1865 /* Start the shell. Set initial character to '-'. */ 1866 argv0[0] = '-'; 1867 1868 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1) 1869 >= sizeof(argv0) - 1) { 1870 errno = EINVAL; 1871 perror(shell); 1872 exit(1); 1873 } 1874 1875 /* Execute the shell. */ 1876 argv[0] = argv0; 1877 argv[1] = NULL; 1878 execve(shell, argv, env); 1879 1880 /* Executing the shell failed. */ 1881 perror(shell); 1882 exit(1); 1883 } 1884 /* 1885 * Execute the command using the user's shell. This uses the -c 1886 * option to execute the command. 1887 */ 1888 argv[0] = (char *) shell0; 1889 argv[1] = "-c"; 1890 argv[2] = (char *) command; 1891 argv[3] = NULL; 1892 execve(shell, argv, env); 1893 perror(shell); 1894 exit(1); 1895 } 1896 1897 void 1898 session_unused(int id) 1899 { 1900 debug3("%s: session id %d unused", __func__, id); 1901 if (id >= options.max_sessions || 1902 id >= sessions_nalloc) { 1903 fatal("%s: insane session id %d (max %d nalloc %d)", 1904 __func__, id, options.max_sessions, sessions_nalloc); 1905 } 1906 memset(&sessions[id], 0, sizeof(*sessions)); 1907 sessions[id].self = id; 1908 sessions[id].used = 0; 1909 sessions[id].chanid = -1; 1910 sessions[id].ptyfd = -1; 1911 sessions[id].ttyfd = -1; 1912 sessions[id].ptymaster = -1; 1913 sessions[id].x11_chanids = NULL; 1914 sessions[id].next_unused = sessions_first_unused; 1915 sessions_first_unused = id; 1916 } 1917 1918 Session * 1919 session_new(void) 1920 { 1921 Session *s, *tmp; 1922 1923 if (sessions_first_unused == -1) { 1924 if (sessions_nalloc >= options.max_sessions) 1925 return NULL; 1926 debug2("%s: allocate (allocated %d max %d)", 1927 __func__, sessions_nalloc, options.max_sessions); 1928 tmp = xrealloc(sessions, sessions_nalloc + 1, 1929 sizeof(*sessions)); 1930 if (tmp == NULL) { 1931 error("%s: cannot allocate %d sessions", 1932 __func__, sessions_nalloc + 1); 1933 return NULL; 1934 } 1935 sessions = tmp; 1936 session_unused(sessions_nalloc++); 1937 } 1938 1939 if (sessions_first_unused >= sessions_nalloc || 1940 sessions_first_unused < 0) { 1941 fatal("%s: insane first_unused %d max %d nalloc %d", 1942 __func__, sessions_first_unused, options.max_sessions, 1943 sessions_nalloc); 1944 } 1945 1946 s = &sessions[sessions_first_unused]; 1947 if (s->used) { 1948 fatal("%s: session %d already used", 1949 __func__, sessions_first_unused); 1950 } 1951 sessions_first_unused = s->next_unused; 1952 s->used = 1; 1953 s->next_unused = -1; 1954 debug("session_new: session %d", s->self); 1955 1956 return s; 1957 } 1958 1959 static void 1960 session_dump(void) 1961 { 1962 int i; 1963 for (i = 0; i < sessions_nalloc; i++) { 1964 Session *s = &sessions[i]; 1965 1966 debug("dump: used %d next_unused %d session %d %p " 1967 "channel %d pid %ld", 1968 s->used, 1969 s->next_unused, 1970 s->self, 1971 s, 1972 s->chanid, 1973 (long)s->pid); 1974 } 1975 } 1976 1977 int 1978 session_open(Authctxt *authctxt, int chanid) 1979 { 1980 Session *s = session_new(); 1981 debug("session_open: channel %d", chanid); 1982 if (s == NULL) { 1983 error("no more sessions"); 1984 return 0; 1985 } 1986 s->authctxt = authctxt; 1987 s->pw = authctxt->pw; 1988 if (s->pw == NULL || !authctxt->valid) 1989 fatal("no user for session %d", s->self); 1990 debug("session_open: session %d: link with channel %d", s->self, chanid); 1991 s->chanid = chanid; 1992 return 1; 1993 } 1994 1995 Session * 1996 session_by_tty(char *tty) 1997 { 1998 int i; 1999 for (i = 0; i < sessions_nalloc; i++) { 2000 Session *s = &sessions[i]; 2001 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) { 2002 debug("session_by_tty: session %d tty %s", i, tty); 2003 return s; 2004 } 2005 } 2006 debug("session_by_tty: unknown tty %.100s", tty); 2007 session_dump(); 2008 return NULL; 2009 } 2010 2011 static Session * 2012 session_by_channel(int id) 2013 { 2014 int i; 2015 for (i = 0; i < sessions_nalloc; i++) { 2016 Session *s = &sessions[i]; 2017 if (s->used && s->chanid == id) { 2018 debug("session_by_channel: session %d channel %d", 2019 i, id); 2020 return s; 2021 } 2022 } 2023 debug("session_by_channel: unknown channel %d", id); 2024 session_dump(); 2025 return NULL; 2026 } 2027 2028 static Session * 2029 session_by_x11_channel(int id) 2030 { 2031 int i, j; 2032 2033 for (i = 0; i < sessions_nalloc; i++) { 2034 Session *s = &sessions[i]; 2035 2036 if (s->x11_chanids == NULL || !s->used) 2037 continue; 2038 for (j = 0; s->x11_chanids[j] != -1; j++) { 2039 if (s->x11_chanids[j] == id) { 2040 debug("session_by_x11_channel: session %d " 2041 "channel %d", s->self, id); 2042 return s; 2043 } 2044 } 2045 } 2046 debug("session_by_x11_channel: unknown channel %d", id); 2047 session_dump(); 2048 return NULL; 2049 } 2050 2051 static Session * 2052 session_by_pid(pid_t pid) 2053 { 2054 int i; 2055 debug("session_by_pid: pid %ld", (long)pid); 2056 for (i = 0; i < sessions_nalloc; i++) { 2057 Session *s = &sessions[i]; 2058 if (s->used && s->pid == pid) 2059 return s; 2060 } 2061 error("session_by_pid: unknown pid %ld", (long)pid); 2062 session_dump(); 2063 return NULL; 2064 } 2065 2066 static int 2067 session_window_change_req(Session *s) 2068 { 2069 s->col = packet_get_int(); 2070 s->row = packet_get_int(); 2071 s->xpixel = packet_get_int(); 2072 s->ypixel = packet_get_int(); 2073 packet_check_eom(); 2074 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel); 2075 return 1; 2076 } 2077 2078 static int 2079 session_pty_req(Session *s) 2080 { 2081 u_int len; 2082 int n_bytes; 2083 2084 if (no_pty_flag || !options.permit_tty) { 2085 debug("Allocating a pty not permitted for this authentication."); 2086 return 0; 2087 } 2088 if (s->ttyfd != -1) { 2089 packet_disconnect("Protocol error: you already have a pty."); 2090 return 0; 2091 } 2092 2093 s->term = packet_get_string(&len); 2094 2095 if (compat20) { 2096 s->col = packet_get_int(); 2097 s->row = packet_get_int(); 2098 } else { 2099 s->row = packet_get_int(); 2100 s->col = packet_get_int(); 2101 } 2102 s->xpixel = packet_get_int(); 2103 s->ypixel = packet_get_int(); 2104 2105 if (strcmp(s->term, "") == 0) { 2106 free(s->term); 2107 s->term = NULL; 2108 } 2109 2110 /* Allocate a pty and open it. */ 2111 debug("Allocating pty."); 2112 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, 2113 sizeof(s->tty)))) { 2114 free(s->term); 2115 s->term = NULL; 2116 s->ptyfd = -1; 2117 s->ttyfd = -1; 2118 error("session_pty_req: session %d alloc failed", s->self); 2119 return 0; 2120 } 2121 debug("session_pty_req: session %d alloc %s", s->self, s->tty); 2122 2123 /* for SSH1 the tty modes length is not given */ 2124 if (!compat20) 2125 n_bytes = packet_remaining(); 2126 tty_parse_modes(s->ttyfd, &n_bytes); 2127 2128 if (!use_privsep) 2129 pty_setowner(s->pw, s->tty); 2130 2131 /* Set window size from the packet. */ 2132 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel); 2133 2134 packet_check_eom(); 2135 session_proctitle(s); 2136 return 1; 2137 } 2138 2139 static int 2140 session_subsystem_req(Session *s) 2141 { 2142 struct stat st; 2143 u_int len; 2144 int success = 0; 2145 char *prog, *cmd; 2146 u_int i; 2147 2148 s->subsys = packet_get_string(&len); 2149 packet_check_eom(); 2150 debug2("subsystem request for %.100s by user %s", s->subsys, 2151 s->pw->pw_name); 2152 2153 for (i = 0; i < options.num_subsystems; i++) { 2154 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) { 2155 prog = options.subsystem_command[i]; 2156 cmd = options.subsystem_args[i]; 2157 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) { 2158 s->is_subsystem = SUBSYSTEM_INT_SFTP; 2159 debug("subsystem: %s", prog); 2160 } else { 2161 if (stat(prog, &st) < 0) 2162 debug("subsystem: cannot stat %s: %s", 2163 prog, strerror(errno)); 2164 s->is_subsystem = SUBSYSTEM_EXT; 2165 debug("subsystem: exec() %s", cmd); 2166 } 2167 success = do_exec(s, cmd) == 0; 2168 break; 2169 } 2170 } 2171 2172 if (!success) 2173 logit("subsystem request for %.100s by user %s failed, " 2174 "subsystem not found", s->subsys, s->pw->pw_name); 2175 2176 return success; 2177 } 2178 2179 static int 2180 session_x11_req(Session *s) 2181 { 2182 int success; 2183 2184 if (s->auth_proto != NULL || s->auth_data != NULL) { 2185 error("session_x11_req: session %d: " 2186 "x11 forwarding already active", s->self); 2187 return 0; 2188 } 2189 s->single_connection = packet_get_char(); 2190 s->auth_proto = packet_get_string(NULL); 2191 s->auth_data = packet_get_string(NULL); 2192 s->screen = packet_get_int(); 2193 packet_check_eom(); 2194 2195 success = session_setup_x11fwd(s); 2196 if (!success) { 2197 free(s->auth_proto); 2198 free(s->auth_data); 2199 s->auth_proto = NULL; 2200 s->auth_data = NULL; 2201 } 2202 return success; 2203 } 2204 2205 static int 2206 session_shell_req(Session *s) 2207 { 2208 packet_check_eom(); 2209 return do_exec(s, NULL) == 0; 2210 } 2211 2212 static int 2213 session_exec_req(Session *s) 2214 { 2215 u_int len, success; 2216 2217 char *command = packet_get_string(&len); 2218 packet_check_eom(); 2219 success = do_exec(s, command) == 0; 2220 free(command); 2221 return success; 2222 } 2223 2224 static int 2225 session_break_req(Session *s) 2226 { 2227 2228 packet_get_int(); /* ignored */ 2229 packet_check_eom(); 2230 2231 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) < 0) 2232 return 0; 2233 return 1; 2234 } 2235 2236 static int 2237 session_env_req(Session *s) 2238 { 2239 char *name, *val; 2240 u_int name_len, val_len, i; 2241 2242 name = packet_get_cstring(&name_len); 2243 val = packet_get_cstring(&val_len); 2244 packet_check_eom(); 2245 2246 /* Don't set too many environment variables */ 2247 if (s->num_env > 128) { 2248 debug2("Ignoring env request %s: too many env vars", name); 2249 goto fail; 2250 } 2251 2252 for (i = 0; i < options.num_accept_env; i++) { 2253 if (match_pattern(name, options.accept_env[i])) { 2254 debug2("Setting env %d: %s=%s", s->num_env, name, val); 2255 s->env = xrealloc(s->env, s->num_env + 1, 2256 sizeof(*s->env)); 2257 s->env[s->num_env].name = name; 2258 s->env[s->num_env].val = val; 2259 s->num_env++; 2260 return (1); 2261 } 2262 } 2263 debug2("Ignoring env request %s: disallowed name", name); 2264 2265 fail: 2266 free(name); 2267 free(val); 2268 return (0); 2269 } 2270 2271 static int 2272 session_auth_agent_req(Session *s) 2273 { 2274 static int called = 0; 2275 packet_check_eom(); 2276 if (no_agent_forwarding_flag || !options.allow_agent_forwarding) { 2277 debug("session_auth_agent_req: no_agent_forwarding_flag"); 2278 return 0; 2279 } 2280 if (called) { 2281 return 0; 2282 } else { 2283 called = 1; 2284 return auth_input_request_forwarding(s->pw); 2285 } 2286 } 2287 2288 int 2289 session_input_channel_req(Channel *c, const char *rtype) 2290 { 2291 int success = 0; 2292 Session *s; 2293 2294 if ((s = session_by_channel(c->self)) == NULL) { 2295 logit("session_input_channel_req: no session %d req %.100s", 2296 c->self, rtype); 2297 return 0; 2298 } 2299 debug("session_input_channel_req: session %d req %s", s->self, rtype); 2300 2301 /* 2302 * a session is in LARVAL state until a shell, a command 2303 * or a subsystem is executed 2304 */ 2305 if (c->type == SSH_CHANNEL_LARVAL) { 2306 if (strcmp(rtype, "shell") == 0) { 2307 success = session_shell_req(s); 2308 } else if (strcmp(rtype, "exec") == 0) { 2309 success = session_exec_req(s); 2310 } else if (strcmp(rtype, "pty-req") == 0) { 2311 success = session_pty_req(s); 2312 } else if (strcmp(rtype, "x11-req") == 0) { 2313 success = session_x11_req(s); 2314 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) { 2315 success = session_auth_agent_req(s); 2316 } else if (strcmp(rtype, "subsystem") == 0) { 2317 success = session_subsystem_req(s); 2318 } else if (strcmp(rtype, "env") == 0) { 2319 success = session_env_req(s); 2320 } 2321 } 2322 if (strcmp(rtype, "window-change") == 0) { 2323 success = session_window_change_req(s); 2324 } else if (strcmp(rtype, "break") == 0) { 2325 success = session_break_req(s); 2326 } 2327 2328 return success; 2329 } 2330 2331 void 2332 session_set_fds(Session *s, int fdin, int fdout, int fderr, int ignore_fderr, 2333 int is_tty) 2334 { 2335 if (!compat20) 2336 fatal("session_set_fds: called for proto != 2.0"); 2337 /* 2338 * now that have a child and a pipe to the child, 2339 * we can activate our channel and register the fd's 2340 */ 2341 if (s->chanid == -1) 2342 fatal("no channel for session %d", s->self); 2343 channel_set_fds(s->chanid, 2344 fdout, fdin, fderr, 2345 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ, 2346 1, is_tty, CHAN_SES_WINDOW_DEFAULT); 2347 } 2348 2349 /* 2350 * Function to perform pty cleanup. Also called if we get aborted abnormally 2351 * (e.g., due to a dropped connection). 2352 */ 2353 void 2354 session_pty_cleanup2(Session *s) 2355 { 2356 if (s == NULL) { 2357 error("session_pty_cleanup: no session"); 2358 return; 2359 } 2360 if (s->ttyfd == -1) 2361 return; 2362 2363 debug("session_pty_cleanup: session %d release %s", s->self, s->tty); 2364 2365 /* Record that the user has logged out. */ 2366 if (s->pid != 0) 2367 record_logout(s->pid, s->tty, s->pw->pw_name); 2368 2369 /* Release the pseudo-tty. */ 2370 if (getuid() == 0) 2371 pty_release(s->tty); 2372 2373 /* 2374 * Close the server side of the socket pairs. We must do this after 2375 * the pty cleanup, so that another process doesn't get this pty 2376 * while we're still cleaning up. 2377 */ 2378 if (s->ptymaster != -1 && close(s->ptymaster) < 0) 2379 error("close(s->ptymaster/%d): %s", 2380 s->ptymaster, strerror(errno)); 2381 2382 /* unlink pty from session */ 2383 s->ttyfd = -1; 2384 } 2385 2386 void 2387 session_pty_cleanup(Session *s) 2388 { 2389 PRIVSEP(session_pty_cleanup2(s)); 2390 } 2391 2392 static char * 2393 sig2name(int sig) 2394 { 2395 #define SSH_SIG(x) if (sig == SIG ## x) return #x 2396 SSH_SIG(ABRT); 2397 SSH_SIG(ALRM); 2398 SSH_SIG(FPE); 2399 SSH_SIG(HUP); 2400 SSH_SIG(ILL); 2401 SSH_SIG(INT); 2402 SSH_SIG(KILL); 2403 SSH_SIG(PIPE); 2404 SSH_SIG(QUIT); 2405 SSH_SIG(SEGV); 2406 SSH_SIG(TERM); 2407 SSH_SIG(USR1); 2408 SSH_SIG(USR2); 2409 #undef SSH_SIG 2410 return "SIG@openssh.com"; 2411 } 2412 2413 static void 2414 session_close_x11(int id) 2415 { 2416 Channel *c; 2417 2418 if ((c = channel_by_id(id)) == NULL) { 2419 debug("session_close_x11: x11 channel %d missing", id); 2420 } else { 2421 /* Detach X11 listener */ 2422 debug("session_close_x11: detach x11 channel %d", id); 2423 channel_cancel_cleanup(id); 2424 if (c->ostate != CHAN_OUTPUT_CLOSED) 2425 chan_mark_dead(c); 2426 } 2427 } 2428 2429 static void 2430 session_close_single_x11(int id, void *arg) 2431 { 2432 Session *s; 2433 u_int i; 2434 2435 debug3("session_close_single_x11: channel %d", id); 2436 channel_cancel_cleanup(id); 2437 if ((s = session_by_x11_channel(id)) == NULL) 2438 fatal("session_close_single_x11: no x11 channel %d", id); 2439 for (i = 0; s->x11_chanids[i] != -1; i++) { 2440 debug("session_close_single_x11: session %d: " 2441 "closing channel %d", s->self, s->x11_chanids[i]); 2442 /* 2443 * The channel "id" is already closing, but make sure we 2444 * close all of its siblings. 2445 */ 2446 if (s->x11_chanids[i] != id) 2447 session_close_x11(s->x11_chanids[i]); 2448 } 2449 free(s->x11_chanids); 2450 s->x11_chanids = NULL; 2451 free(s->display); 2452 s->display = NULL; 2453 free(s->auth_proto); 2454 s->auth_proto = NULL; 2455 free(s->auth_data); 2456 s->auth_data = NULL; 2457 free(s->auth_display); 2458 s->auth_display = NULL; 2459 } 2460 2461 static void 2462 session_exit_message(Session *s, int status) 2463 { 2464 Channel *c; 2465 2466 if ((c = channel_lookup(s->chanid)) == NULL) 2467 fatal("session_exit_message: session %d: no channel %d", 2468 s->self, s->chanid); 2469 debug("session_exit_message: session %d channel %d pid %ld", 2470 s->self, s->chanid, (long)s->pid); 2471 2472 if (WIFEXITED(status)) { 2473 channel_request_start(s->chanid, "exit-status", 0); 2474 packet_put_int(WEXITSTATUS(status)); 2475 packet_send(); 2476 } else if (WIFSIGNALED(status)) { 2477 channel_request_start(s->chanid, "exit-signal", 0); 2478 packet_put_cstring(sig2name(WTERMSIG(status))); 2479 #ifdef WCOREDUMP 2480 packet_put_char(WCOREDUMP(status)? 1 : 0); 2481 #else /* WCOREDUMP */ 2482 packet_put_char(0); 2483 #endif /* WCOREDUMP */ 2484 packet_put_cstring(""); 2485 packet_put_cstring(""); 2486 packet_send(); 2487 } else { 2488 /* Some weird exit cause. Just exit. */ 2489 packet_disconnect("wait returned status %04x.", status); 2490 } 2491 2492 /* disconnect channel */ 2493 debug("session_exit_message: release channel %d", s->chanid); 2494 2495 /* 2496 * Adjust cleanup callback attachment to send close messages when 2497 * the channel gets EOF. The session will be then be closed 2498 * by session_close_by_channel when the childs close their fds. 2499 */ 2500 channel_register_cleanup(c->self, session_close_by_channel, 1); 2501 2502 /* 2503 * emulate a write failure with 'chan_write_failed', nobody will be 2504 * interested in data we write. 2505 * Note that we must not call 'chan_read_failed', since there could 2506 * be some more data waiting in the pipe. 2507 */ 2508 if (c->ostate != CHAN_OUTPUT_CLOSED) 2509 chan_write_failed(c); 2510 } 2511 2512 void 2513 session_close(Session *s) 2514 { 2515 u_int i; 2516 2517 debug("session_close: session %d pid %ld", s->self, (long)s->pid); 2518 if (s->ttyfd != -1) 2519 session_pty_cleanup(s); 2520 free(s->term); 2521 free(s->display); 2522 free(s->x11_chanids); 2523 free(s->auth_display); 2524 free(s->auth_data); 2525 free(s->auth_proto); 2526 free(s->subsys); 2527 if (s->env != NULL) { 2528 for (i = 0; i < s->num_env; i++) { 2529 free(s->env[i].name); 2530 free(s->env[i].val); 2531 } 2532 free(s->env); 2533 } 2534 session_proctitle(s); 2535 session_unused(s->self); 2536 } 2537 2538 void 2539 session_close_by_pid(pid_t pid, int status) 2540 { 2541 Session *s = session_by_pid(pid); 2542 if (s == NULL) { 2543 debug("session_close_by_pid: no session for pid %ld", 2544 (long)pid); 2545 return; 2546 } 2547 if (s->chanid != -1) 2548 session_exit_message(s, status); 2549 if (s->ttyfd != -1) 2550 session_pty_cleanup(s); 2551 s->pid = 0; 2552 } 2553 2554 /* 2555 * this is called when a channel dies before 2556 * the session 'child' itself dies 2557 */ 2558 void 2559 session_close_by_channel(int id, void *arg) 2560 { 2561 Session *s = session_by_channel(id); 2562 u_int i; 2563 2564 if (s == NULL) { 2565 debug("session_close_by_channel: no session for id %d", id); 2566 return; 2567 } 2568 debug("session_close_by_channel: channel %d child %ld", 2569 id, (long)s->pid); 2570 if (s->pid != 0) { 2571 debug("session_close_by_channel: channel %d: has child", id); 2572 /* 2573 * delay detach of session, but release pty, since 2574 * the fd's to the child are already closed 2575 */ 2576 if (s->ttyfd != -1) 2577 session_pty_cleanup(s); 2578 return; 2579 } 2580 /* detach by removing callback */ 2581 channel_cancel_cleanup(s->chanid); 2582 2583 /* Close any X11 listeners associated with this session */ 2584 if (s->x11_chanids != NULL) { 2585 for (i = 0; s->x11_chanids[i] != -1; i++) { 2586 session_close_x11(s->x11_chanids[i]); 2587 s->x11_chanids[i] = -1; 2588 } 2589 } 2590 2591 s->chanid = -1; 2592 session_close(s); 2593 } 2594 2595 void 2596 session_destroy_all(void (*closefunc)(Session *)) 2597 { 2598 int i; 2599 for (i = 0; i < sessions_nalloc; i++) { 2600 Session *s = &sessions[i]; 2601 if (s->used) { 2602 if (closefunc != NULL) 2603 closefunc(s); 2604 else 2605 session_close(s); 2606 } 2607 } 2608 } 2609 2610 static char * 2611 session_tty_list(void) 2612 { 2613 static char buf[1024]; 2614 int i; 2615 char *cp; 2616 2617 buf[0] = '\0'; 2618 for (i = 0; i < sessions_nalloc; i++) { 2619 Session *s = &sessions[i]; 2620 if (s->used && s->ttyfd != -1) { 2621 2622 if (strncmp(s->tty, "/dev/", 5) != 0) { 2623 cp = strrchr(s->tty, '/'); 2624 cp = (cp == NULL) ? s->tty : cp + 1; 2625 } else 2626 cp = s->tty + 5; 2627 2628 if (buf[0] != '\0') 2629 strlcat(buf, ",", sizeof buf); 2630 strlcat(buf, cp, sizeof buf); 2631 } 2632 } 2633 if (buf[0] == '\0') 2634 strlcpy(buf, "notty", sizeof buf); 2635 return buf; 2636 } 2637 2638 void 2639 session_proctitle(Session *s) 2640 { 2641 if (s->pw == NULL) 2642 error("no user for session %d", s->self); 2643 else 2644 setproctitle("%s@%s", s->pw->pw_name, session_tty_list()); 2645 } 2646 2647 int 2648 session_setup_x11fwd(Session *s) 2649 { 2650 struct stat st; 2651 char display[512], auth_display[512]; 2652 char hostname[NI_MAXHOST]; 2653 u_int i; 2654 2655 if (no_x11_forwarding_flag) { 2656 packet_send_debug("X11 forwarding disabled in user configuration file."); 2657 return 0; 2658 } 2659 if (!options.x11_forwarding) { 2660 debug("X11 forwarding disabled in server configuration file."); 2661 return 0; 2662 } 2663 if (!options.xauth_location || 2664 (stat(options.xauth_location, &st) == -1)) { 2665 packet_send_debug("No xauth program; cannot forward with spoofing."); 2666 return 0; 2667 } 2668 if (options.use_login) { 2669 packet_send_debug("X11 forwarding disabled; " 2670 "not compatible with UseLogin=yes."); 2671 return 0; 2672 } 2673 if (s->display != NULL) { 2674 debug("X11 display already set."); 2675 return 0; 2676 } 2677 if (x11_create_display_inet(options.x11_display_offset, 2678 options.x11_use_localhost, s->single_connection, 2679 &s->display_number, &s->x11_chanids) == -1) { 2680 debug("x11_create_display_inet failed."); 2681 return 0; 2682 } 2683 for (i = 0; s->x11_chanids[i] != -1; i++) { 2684 channel_register_cleanup(s->x11_chanids[i], 2685 session_close_single_x11, 0); 2686 } 2687 2688 /* Set up a suitable value for the DISPLAY variable. */ 2689 if (gethostname(hostname, sizeof(hostname)) < 0) 2690 fatal("gethostname: %.100s", strerror(errno)); 2691 /* 2692 * auth_display must be used as the displayname when the 2693 * authorization entry is added with xauth(1). This will be 2694 * different than the DISPLAY string for localhost displays. 2695 */ 2696 if (options.x11_use_localhost) { 2697 snprintf(display, sizeof display, "localhost:%u.%u", 2698 s->display_number, s->screen); 2699 snprintf(auth_display, sizeof auth_display, "unix:%u.%u", 2700 s->display_number, s->screen); 2701 s->display = xstrdup(display); 2702 s->auth_display = xstrdup(auth_display); 2703 } else { 2704 #ifdef IPADDR_IN_DISPLAY 2705 struct hostent *he; 2706 struct in_addr my_addr; 2707 2708 he = gethostbyname(hostname); 2709 if (he == NULL) { 2710 error("Can't get IP address for X11 DISPLAY."); 2711 packet_send_debug("Can't get IP address for X11 DISPLAY."); 2712 return 0; 2713 } 2714 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr)); 2715 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr), 2716 s->display_number, s->screen); 2717 #else 2718 snprintf(display, sizeof display, "%.400s:%u.%u", hostname, 2719 s->display_number, s->screen); 2720 #endif 2721 s->display = xstrdup(display); 2722 s->auth_display = xstrdup(display); 2723 } 2724 2725 return 1; 2726 } 2727 2728 static void 2729 do_authenticated2(Authctxt *authctxt) 2730 { 2731 server_loop2(authctxt); 2732 } 2733 2734 void 2735 do_cleanup(Authctxt *authctxt) 2736 { 2737 static int called = 0; 2738 2739 debug("do_cleanup"); 2740 2741 /* no cleanup if we're in the child for login shell */ 2742 if (is_child) 2743 return; 2744 2745 /* avoid double cleanup */ 2746 if (called) 2747 return; 2748 called = 1; 2749 2750 if (authctxt == NULL) 2751 return; 2752 2753 #ifdef USE_PAM 2754 if (options.use_pam) { 2755 sshpam_cleanup(); 2756 sshpam_thread_cleanup(); 2757 } 2758 #endif 2759 2760 if (!authctxt->authenticated) 2761 return; 2762 2763 #ifdef KRB5 2764 if (options.kerberos_ticket_cleanup && 2765 authctxt->krb5_ctx) 2766 krb5_cleanup_proc(authctxt); 2767 #endif 2768 2769 #ifdef GSSAPI 2770 if (compat20 && options.gss_cleanup_creds) 2771 ssh_gssapi_cleanup_creds(); 2772 #endif 2773 2774 /* remove agent socket */ 2775 auth_sock_cleanup_proc(authctxt->pw); 2776 2777 /* 2778 * Cleanup ptys/utmp only if privsep is disabled, 2779 * or if running in monitor. 2780 */ 2781 if (!use_privsep || mm_is_monitor()) 2782 session_destroy_all(session_pty_cleanup2); 2783 } 2784