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