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