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