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