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