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