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