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