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