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