OSDN Git Service

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