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