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