]> andersk Git - gssapi-openssh.git/blob - openssh/session.c
merged OpenSSH 3.7.1p2 to trunk
[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", _PATH_STDPATH);
1163                 else
1164                         child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1165 #else /* HAVE_LOGIN_CAP */
1166 # ifndef HAVE_CYGWIN
1167                 /*
1168                  * There's no standard path on Windows. The path contains
1169                  * important components pointing to the system directories,
1170                  * needed for loading shared libraries. So the path better
1171                  * remains intact here.
1172                  */
1173                 if (getenv("LD_LIBRARY_PATH"))
1174                         child_set_env(&env, &envsize, "LD_LIBRARY_PATH",
1175                                       getenv("LD_LIBRARY_PATH"));
1176 #  ifdef HAVE_ETC_DEFAULT_LOGIN
1177                 read_etc_default_login(&env, &envsize, pw->pw_uid);
1178                 path = child_get_env(env, "PATH");
1179 #  endif /* HAVE_ETC_DEFAULT_LOGIN */
1180                 if (path == NULL || *path == '\0') {
1181                         child_set_env(&env, &envsize, "PATH", 
1182                             s->pw->pw_uid == 0 ?
1183                                 SUPERUSER_PATH : _PATH_STDPATH);
1184                 }
1185 # endif /* HAVE_CYGWIN */
1186 #endif /* HAVE_LOGIN_CAP */
1187
1188                 snprintf(buf, sizeof buf, "%.200s/%.50s",
1189                          _PATH_MAILDIR, pw->pw_name);
1190                 child_set_env(&env, &envsize, "MAIL", buf);
1191
1192                 /* Normal systems set SHELL by default. */
1193                 child_set_env(&env, &envsize, "SHELL", shell);
1194         }
1195         if (getenv("TZ"))
1196                 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1197
1198         /* Set custom environment options from RSA authentication. */
1199         if (!options.use_login) {
1200                 while (custom_environment) {
1201                         struct envstring *ce = custom_environment;
1202                         char *str = ce->s;
1203
1204                         for (i = 0; str[i] != '=' && str[i]; i++)
1205                                 ;
1206                         if (str[i] == '=') {
1207                                 str[i] = 0;
1208                                 child_set_env(&env, &envsize, str, str + i + 1);
1209                         }
1210                         custom_environment = ce->next;
1211                         xfree(ce->s);
1212                         xfree(ce);
1213                 }
1214         }
1215
1216         /* SSH_CLIENT deprecated */
1217         snprintf(buf, sizeof buf, "%.50s %d %d",
1218             get_remote_ipaddr(), get_remote_port(), get_local_port());
1219         child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1220
1221         laddr = get_local_ipaddr(packet_get_connection_in());
1222         snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1223             get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1224         xfree(laddr);
1225         child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1226
1227         if (s->ttyfd != -1)
1228                 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1229         if (s->term)
1230                 child_set_env(&env, &envsize, "TERM", s->term);
1231         if (s->display)
1232                 child_set_env(&env, &envsize, "DISPLAY", s->display);
1233         if (original_command)
1234                 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1235                     original_command);
1236
1237 #ifdef _UNICOS
1238         if (cray_tmpdir[0] != '\0')
1239                 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1240 #endif /* _UNICOS */
1241
1242 #ifdef _AIX
1243         {
1244                 char *cp;
1245
1246                 if ((cp = getenv("AUTHSTATE")) != NULL)
1247                         child_set_env(&env, &envsize, "AUTHSTATE", cp);
1248                 if ((cp = getenv("KRB5CCNAME")) != NULL)
1249                         child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1250                 read_environment_file(&env, &envsize, "/etc/environment");
1251         }
1252 #endif
1253 #ifdef KRB5
1254         if (s->authctxt->krb5_ticket_file)
1255                 child_set_env(&env, &envsize, "KRB5CCNAME",
1256                     s->authctxt->krb5_ticket_file);
1257 #endif
1258 #ifdef USE_PAM
1259         /*
1260          * Pull in any environment variables that may have
1261          * been set by PAM.
1262          */
1263         if (options.use_pam) {
1264                 char **p = fetch_pam_environment();
1265
1266                 copy_environment(p, &env, &envsize);
1267                 free_pam_environment(p);
1268         }
1269 #endif /* USE_PAM */
1270
1271         if (auth_sock_name != NULL)
1272                 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1273                     auth_sock_name);
1274
1275         /* read $HOME/.ssh/environment. */
1276         if (options.permit_user_env && !options.use_login) {
1277                 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1278                     strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1279                 read_environment_file(&env, &envsize, buf);
1280         }
1281         if (debug_flag) {
1282                 /* dump the environment */
1283                 fprintf(stderr, "Environment:\n");
1284                 for (i = 0; env[i]; i++)
1285                         fprintf(stderr, "  %.200s\n", env[i]);
1286         }
1287         return env;
1288 }
1289
1290 /*
1291  * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1292  * first in this order).
1293  */
1294 static void
1295 do_rc_files(Session *s, const char *shell)
1296 {
1297         FILE *f = NULL;
1298         char cmd[1024];
1299         int do_xauth;
1300         struct stat st;
1301
1302         do_xauth =
1303             s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1304
1305         /* ignore _PATH_SSH_USER_RC for subsystems */
1306         if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1307                 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1308                     shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1309                 if (debug_flag)
1310                         fprintf(stderr, "Running %s\n", cmd);
1311                 f = popen(cmd, "w");
1312                 if (f) {
1313                         if (do_xauth)
1314                                 fprintf(f, "%s %s\n", s->auth_proto,
1315                                     s->auth_data);
1316                         pclose(f);
1317                 } else
1318                         fprintf(stderr, "Could not run %s\n",
1319                             _PATH_SSH_USER_RC);
1320         } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1321                 if (debug_flag)
1322                         fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1323                             _PATH_SSH_SYSTEM_RC);
1324                 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1325                 if (f) {
1326                         if (do_xauth)
1327                                 fprintf(f, "%s %s\n", s->auth_proto,
1328                                     s->auth_data);
1329                         pclose(f);
1330                 } else
1331                         fprintf(stderr, "Could not run %s\n",
1332                             _PATH_SSH_SYSTEM_RC);
1333         } else if (do_xauth && options.xauth_location != NULL) {
1334                 /* Add authority data to .Xauthority if appropriate. */
1335                 if (debug_flag) {
1336                         fprintf(stderr,
1337                             "Running %.500s remove %.100s\n",
1338                             options.xauth_location, s->auth_display);
1339                         fprintf(stderr,
1340                             "%.500s add %.100s %.100s %.100s\n",
1341                             options.xauth_location, s->auth_display,
1342                             s->auth_proto, s->auth_data);
1343                 }
1344                 snprintf(cmd, sizeof cmd, "%s -q -",
1345                     options.xauth_location);
1346                 f = popen(cmd, "w");
1347                 if (f) {
1348                         fprintf(f, "remove %s\n",
1349                             s->auth_display);
1350                         fprintf(f, "add %s %s %s\n",
1351                             s->auth_display, s->auth_proto,
1352                             s->auth_data);
1353                         pclose(f);
1354                 } else {
1355                         fprintf(stderr, "Could not run %s\n",
1356                             cmd);
1357                 }
1358         }
1359 }
1360
1361 static void
1362 do_nologin(struct passwd *pw)
1363 {
1364         FILE *f = NULL;
1365         char buf[1024];
1366
1367 #ifdef HAVE_LOGIN_CAP
1368         if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1369                 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1370                     _PATH_NOLOGIN), "r");
1371 #else
1372         if (pw->pw_uid)
1373                 f = fopen(_PATH_NOLOGIN, "r");
1374 #endif
1375         if (f) {
1376                 /* /etc/nologin exists.  Print its contents and exit. */
1377                 logit("User %.100s not allowed because %s exists",
1378                     pw->pw_name, _PATH_NOLOGIN);
1379                 while (fgets(buf, sizeof(buf), f))
1380                         fputs(buf, stderr);
1381                 fclose(f);
1382                 fflush(NULL);
1383                 exit(254);
1384         }
1385 }
1386
1387 /* Set login name, uid, gid, and groups. */
1388 void
1389 do_setusercontext(struct passwd *pw)
1390 {
1391 #ifndef HAVE_CYGWIN
1392         if (getuid() == 0 || geteuid() == 0)
1393 #endif /* HAVE_CYGWIN */
1394         {
1395
1396 #ifdef HAVE_SETPCRED
1397                 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1398                         fatal("Failed to set process credentials");
1399 #endif /* HAVE_SETPCRED */
1400 #ifdef HAVE_LOGIN_CAP
1401 # ifdef __bsdi__
1402                 setpgid(0, 0);
1403 # endif
1404                 if (setusercontext(lc, pw, pw->pw_uid,
1405                     (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1406                         perror("unable to set user context");
1407                         exit(1);
1408                 }
1409 #else
1410 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1411                 /* Sets login uid for accounting */
1412                 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1413                         error("setluid: %s", strerror(errno));
1414 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1415
1416                 if (setlogin(pw->pw_name) < 0)
1417                         error("setlogin failed: %s", strerror(errno));
1418                 if (setgid(pw->pw_gid) < 0) {
1419                         perror("setgid");
1420                         exit(1);
1421                 }
1422                 /* Initialize the group list. */
1423                 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1424                         perror("initgroups");
1425                         exit(1);
1426                 }
1427                 endgrent();
1428 # ifdef USE_PAM
1429                 /*
1430                  * PAM credentials may take the form of supplementary groups. 
1431                  * These will have been wiped by the above initgroups() call.
1432                  * Reestablish them here.
1433                  */
1434                 if (options.use_pam) {
1435                         do_pam_session();
1436                         do_pam_setcred(0);
1437                 }
1438 # endif /* USE_PAM */
1439 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1440                 irix_setusercontext(pw);
1441 #  endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1442 # ifdef _AIX
1443                 aix_usrinfo(pw);
1444 # endif /* _AIX */
1445                 /* Permanently switch to the desired uid. */
1446                 permanently_set_uid(pw);
1447 #endif
1448         }
1449
1450 #ifdef HAVE_CYGWIN
1451         if (is_winnt)
1452 #endif
1453         if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1454                 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1455 }
1456
1457 static void
1458 launch_login(struct passwd *pw, const char *hostname)
1459 {
1460         /* Launch login(1). */
1461
1462         execl(LOGIN_PROGRAM, "login", "-h", hostname,
1463 #ifdef xxxLOGIN_NEEDS_TERM
1464                     (s->term ? s->term : "unknown"),
1465 #endif /* LOGIN_NEEDS_TERM */
1466 #ifdef LOGIN_NO_ENDOPT
1467             "-p", "-f", pw->pw_name, (char *)NULL);
1468 #else
1469             "-p", "-f", "--", pw->pw_name, (char *)NULL);
1470 #endif
1471
1472         /* Login couldn't be executed, die. */
1473
1474         perror("login");
1475         exit(1);
1476 }
1477
1478 /*
1479  * Performs common processing for the child, such as setting up the
1480  * environment, closing extra file descriptors, setting the user and group
1481  * ids, and executing the command or shell.
1482  */
1483 void
1484 do_child(Session *s, const char *command)
1485 {
1486         extern char **environ;
1487         char **env;
1488         char *argv[10];
1489         const char *shell, *shell0, *hostname = NULL;
1490         struct passwd *pw = s->pw;
1491         u_int i;
1492
1493 #ifdef AFS_KRB5
1494 /* Default place to look for aklog. */
1495 #ifdef AKLOG_PATH
1496 #define KPROGDIR AKLOG_PATH
1497 #else
1498 #define KPROGDIR "/usr/bin/aklog"
1499 #endif /* AKLOG_PATH */
1500
1501         struct stat st;
1502         char *aklog_path;
1503 #endif /* AFS_KRB5 */
1504
1505         /* remove hostkey from the child's memory */
1506         destroy_sensitive_data();
1507
1508         /* login(1) is only called if we execute the login shell */
1509         if (options.use_login && command != NULL)
1510                 options.use_login = 0;
1511
1512 #ifdef _UNICOS
1513         cray_setup(pw->pw_uid, pw->pw_name, command);
1514 #endif /* _UNICOS */
1515
1516         /*
1517          * Login(1) does this as well, and it needs uid 0 for the "-h"
1518          * switch, so we let login(1) to this for us.
1519          */
1520         if (!options.use_login) {
1521 #ifdef HAVE_OSF_SIA
1522                 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1523                 if (!check_quietlogin(s, command))
1524                         do_motd();
1525 #else /* HAVE_OSF_SIA */
1526                 do_nologin(pw);
1527                 do_setusercontext(pw);
1528 #endif /* HAVE_OSF_SIA */
1529         }
1530
1531         /*
1532          * Get the shell from the password data.  An empty shell field is
1533          * legal, and means /bin/sh.
1534          */
1535         shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1536
1537         /*
1538          * Make sure $SHELL points to the shell from the password file,
1539          * even if shell is overridden from login.conf
1540          */
1541         env = do_setup_env(s, shell);
1542
1543 #ifdef HAVE_LOGIN_CAP
1544         shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1545 #endif
1546
1547         /* we have to stash the hostname before we close our socket. */
1548         if (options.use_login)
1549                 hostname = get_remote_name_or_ip(utmp_len,
1550                     options.use_dns);
1551         /*
1552          * Close the connection descriptors; note that this is the child, and
1553          * the server will still have the socket open, and it is important
1554          * that we do not shutdown it.  Note that the descriptors cannot be
1555          * closed before building the environment, as we call
1556          * get_remote_ipaddr there.
1557          */
1558         if (packet_get_connection_in() == packet_get_connection_out())
1559                 close(packet_get_connection_in());
1560         else {
1561                 close(packet_get_connection_in());
1562                 close(packet_get_connection_out());
1563         }
1564         /*
1565          * Close all descriptors related to channels.  They will still remain
1566          * open in the parent.
1567          */
1568         /* XXX better use close-on-exec? -markus */
1569         channel_close_all();
1570
1571         /*
1572          * Close any extra file descriptors.  Note that there may still be
1573          * descriptors left by system functions.  They will be closed later.
1574          */
1575         endpwent();
1576
1577         /*
1578          * Close any extra open file descriptors so that we don\'t have them
1579          * hanging around in clients.  Note that we want to do this after
1580          * initgroups, because at least on Solaris 2.3 it leaves file
1581          * descriptors open.
1582          */
1583         for (i = 3; i < 64; i++)
1584                 close(i);
1585
1586         /*
1587          * Must take new environment into use so that .ssh/rc,
1588          * /etc/ssh/sshrc and xauth are run in the proper environment.
1589          */
1590         environ = env;
1591
1592 #ifdef AFS_KRB5
1593
1594         /* User has authenticated, and if a ticket was going to be
1595          * passed we would have it.  KRB5CCNAME should already be set.
1596          * Now try to get an AFS token using aklog.
1597          */
1598         if (k_hasafs()) {  /* Do we have AFS? */
1599
1600                 aklog_path = xstrdup(KPROGDIR);
1601
1602                 /*
1603                  * Make sure it exists before we try to run it
1604                  */
1605                 if (stat(aklog_path, &st) == 0) {
1606                         debug("Running %s to get afs token.",aklog_path);
1607                         system(aklog_path);
1608                 } else {
1609                         debug("%s does not exist.",aklog_path);
1610                 }
1611
1612                 xfree(aklog_path);
1613         }
1614 #endif /* AFS_KRB5 */
1615
1616 #ifdef SESSION_HOOKS
1617         if (options.session_hooks_allow &&
1618             options.session_hooks_startup_cmd)
1619         {
1620             execute_session_hook(options.session_hooks_startup_cmd,
1621                                  s->authctxt,
1622                                  /* startup = */ 1,
1623                                  options.session_hooks_shutdown_cmd != NULL);
1624         }
1625 #endif
1626
1627         /* Change current directory to the user\'s home directory. */
1628         if (chdir(pw->pw_dir) < 0) {
1629                 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1630                     pw->pw_dir, strerror(errno));
1631 #ifdef HAVE_LOGIN_CAP
1632                 if (login_getcapbool(lc, "requirehome", 0))
1633                         exit(1);
1634 #endif
1635         }
1636
1637         if (!options.use_login)
1638                 do_rc_files(s, shell);
1639
1640         /* restore SIGPIPE for child */
1641         signal(SIGPIPE,  SIG_DFL);
1642
1643         if (options.use_login) {
1644                 launch_login(pw, hostname);
1645                 /* NEVERREACHED */
1646         }
1647
1648         /* Get the last component of the shell name. */
1649         if ((shell0 = strrchr(shell, '/')) != NULL)
1650                 shell0++;
1651         else
1652                 shell0 = shell;
1653
1654         /*
1655          * If we have no command, execute the shell.  In this case, the shell
1656          * name to be passed in argv[0] is preceded by '-' to indicate that
1657          * this is a login shell.
1658          */
1659         if (!command) {
1660                 char argv0[256];
1661
1662                 /* Start the shell.  Set initial character to '-'. */
1663                 argv0[0] = '-';
1664
1665                 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1666                     >= sizeof(argv0) - 1) {
1667                         errno = EINVAL;
1668                         perror(shell);
1669                         exit(1);
1670                 }
1671
1672                 /* Execute the shell. */
1673                 argv[0] = argv0;
1674                 argv[1] = NULL;
1675                 execve(shell, argv, environ);
1676
1677                 /* Executing the shell failed. */
1678                 perror(shell);
1679                 exit(1);
1680         }
1681         /*
1682          * Execute the command using the user's shell.  This uses the -c
1683          * option to execute the command.
1684          */
1685         argv[0] = (char *) shell0;
1686         argv[1] = "-c";
1687         argv[2] = (char *) command;
1688         argv[3] = NULL;
1689         execve(shell, argv, environ);
1690         perror(shell);
1691         exit(1);
1692 }
1693
1694 Session *
1695 session_new(void)
1696 {
1697         int i;
1698         static int did_init = 0;
1699         if (!did_init) {
1700                 debug("session_new: init");
1701                 for (i = 0; i < MAX_SESSIONS; i++) {
1702                         sessions[i].used = 0;
1703                 }
1704                 did_init = 1;
1705         }
1706         for (i = 0; i < MAX_SESSIONS; i++) {
1707                 Session *s = &sessions[i];
1708                 if (! s->used) {
1709                         memset(s, 0, sizeof(*s));
1710                         s->chanid = -1;
1711                         s->ptyfd = -1;
1712                         s->ttyfd = -1;
1713                         s->used = 1;
1714                         s->self = i;
1715                         debug("session_new: session %d", i);
1716                         return s;
1717                 }
1718         }
1719         return NULL;
1720 }
1721
1722 static void
1723 session_dump(void)
1724 {
1725         int i;
1726         for (i = 0; i < MAX_SESSIONS; i++) {
1727                 Session *s = &sessions[i];
1728                 debug("dump: used %d session %d %p channel %d pid %ld",
1729                     s->used,
1730                     s->self,
1731                     s,
1732                     s->chanid,
1733                     (long)s->pid);
1734         }
1735 }
1736
1737 int
1738 session_open(Authctxt *authctxt, int chanid)
1739 {
1740         Session *s = session_new();
1741         debug("session_open: channel %d", chanid);
1742         if (s == NULL) {
1743                 error("no more sessions");
1744                 return 0;
1745         }
1746         s->authctxt = authctxt;
1747         s->pw = authctxt->pw;
1748         if (s->pw == NULL)
1749                 fatal("no user for session %d", s->self);
1750         debug("session_open: session %d: link with channel %d", s->self, chanid);
1751         s->chanid = chanid;
1752         return 1;
1753 }
1754
1755 Session *
1756 session_by_tty(char *tty)
1757 {
1758         int i;
1759         for (i = 0; i < MAX_SESSIONS; i++) {
1760                 Session *s = &sessions[i];
1761                 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1762                         debug("session_by_tty: session %d tty %s", i, tty);
1763                         return s;
1764                 }
1765         }
1766         debug("session_by_tty: unknown tty %.100s", tty);
1767         session_dump();
1768         return NULL;
1769 }
1770
1771 static Session *
1772 session_by_channel(int id)
1773 {
1774         int i;
1775         for (i = 0; i < MAX_SESSIONS; i++) {
1776                 Session *s = &sessions[i];
1777                 if (s->used && s->chanid == id) {
1778                         debug("session_by_channel: session %d channel %d", i, id);
1779                         return s;
1780                 }
1781         }
1782         debug("session_by_channel: unknown channel %d", id);
1783         session_dump();
1784         return NULL;
1785 }
1786
1787 static Session *
1788 session_by_pid(pid_t pid)
1789 {
1790         int i;
1791         debug("session_by_pid: pid %ld", (long)pid);
1792         for (i = 0; i < MAX_SESSIONS; i++) {
1793                 Session *s = &sessions[i];
1794                 if (s->used && s->pid == pid)
1795                         return s;
1796         }
1797         error("session_by_pid: unknown pid %ld", (long)pid);
1798         session_dump();
1799         return NULL;
1800 }
1801
1802 static int
1803 session_window_change_req(Session *s)
1804 {
1805         s->col = packet_get_int();
1806         s->row = packet_get_int();
1807         s->xpixel = packet_get_int();
1808         s->ypixel = packet_get_int();
1809         packet_check_eom();
1810         pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1811         return 1;
1812 }
1813
1814 static int
1815 session_pty_req(Session *s)
1816 {
1817         u_int len;
1818         int n_bytes;
1819
1820         if (no_pty_flag) {
1821                 debug("Allocating a pty not permitted for this authentication.");
1822                 return 0;
1823         }
1824         if (s->ttyfd != -1) {
1825                 packet_disconnect("Protocol error: you already have a pty.");
1826                 return 0;
1827         }
1828         /* Get the time and hostname when the user last logged in. */
1829         if (options.print_lastlog) {
1830                 s->hostname[0] = '\0';
1831                 s->last_login_time = get_last_login_time(s->pw->pw_uid,
1832                     s->pw->pw_name, s->hostname, sizeof(s->hostname));
1833         }
1834
1835         s->term = packet_get_string(&len);
1836
1837         if (compat20) {
1838                 s->col = packet_get_int();
1839                 s->row = packet_get_int();
1840         } else {
1841                 s->row = packet_get_int();
1842                 s->col = packet_get_int();
1843         }
1844         s->xpixel = packet_get_int();
1845         s->ypixel = packet_get_int();
1846
1847         if (strcmp(s->term, "") == 0) {
1848                 xfree(s->term);
1849                 s->term = NULL;
1850         }
1851
1852         /* Allocate a pty and open it. */
1853         debug("Allocating pty.");
1854         if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1855                 if (s->term)
1856                         xfree(s->term);
1857                 s->term = NULL;
1858                 s->ptyfd = -1;
1859                 s->ttyfd = -1;
1860                 error("session_pty_req: session %d alloc failed", s->self);
1861                 return 0;
1862         }
1863         debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1864
1865         /* for SSH1 the tty modes length is not given */
1866         if (!compat20)
1867                 n_bytes = packet_remaining();
1868         tty_parse_modes(s->ttyfd, &n_bytes);
1869
1870         /*
1871          * Add a cleanup function to clear the utmp entry and record logout
1872          * time in case we call fatal() (e.g., the connection gets closed).
1873          */
1874         fatal_add_cleanup(session_pty_cleanup, (void *)s);
1875         if (!use_privsep)
1876                 pty_setowner(s->pw, s->tty);
1877
1878         /* Set window size from the packet. */
1879         pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1880
1881         packet_check_eom();
1882         session_proctitle(s);
1883         return 1;
1884 }
1885
1886 static int
1887 session_subsystem_req(Session *s)
1888 {
1889         struct stat st;
1890         u_int len;
1891         int success = 0;
1892         char *cmd, *subsys = packet_get_string(&len);
1893         int i;
1894
1895         packet_check_eom();
1896         logit("subsystem request for %.100s", subsys);
1897
1898         for (i = 0; i < options.num_subsystems; i++) {
1899                 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1900                         cmd = options.subsystem_command[i];
1901                         if (stat(cmd, &st) < 0) {
1902                                 error("subsystem: cannot stat %s: %s", cmd,
1903                                     strerror(errno));
1904                                 break;
1905                         }
1906                         debug("subsystem: exec() %s", cmd);
1907                         s->is_subsystem = 1;
1908                         do_exec(s, cmd);
1909                         success = 1;
1910                         break;
1911                 }
1912         }
1913
1914         if (!success)
1915                 logit("subsystem request for %.100s failed, subsystem not found",
1916                     subsys);
1917
1918         xfree(subsys);
1919         return success;
1920 }
1921
1922 static int
1923 session_x11_req(Session *s)
1924 {
1925         int success;
1926
1927         s->single_connection = packet_get_char();
1928         s->auth_proto = packet_get_string(NULL);
1929         s->auth_data = packet_get_string(NULL);
1930         s->screen = packet_get_int();
1931         packet_check_eom();
1932
1933         success = session_setup_x11fwd(s);
1934         if (!success) {
1935                 xfree(s->auth_proto);
1936                 xfree(s->auth_data);
1937                 s->auth_proto = NULL;
1938                 s->auth_data = NULL;
1939         }
1940         return success;
1941 }
1942
1943 static int
1944 session_shell_req(Session *s)
1945 {
1946         packet_check_eom();
1947         do_exec(s, NULL);
1948         return 1;
1949 }
1950
1951 static int
1952 session_exec_req(Session *s)
1953 {
1954         u_int len;
1955         char *command = packet_get_string(&len);
1956         packet_check_eom();
1957         do_exec(s, command);
1958         xfree(command);
1959         return 1;
1960 }
1961
1962 static int
1963 session_break_req(Session *s)
1964 {
1965         u_int break_length;
1966
1967         break_length = packet_get_int();        /* ignored */
1968         packet_check_eom();
1969
1970         if (s->ttyfd == -1 ||
1971             tcsendbreak(s->ttyfd, 0) < 0)
1972                 return 0;
1973         return 1;
1974 }
1975
1976 static int
1977 session_auth_agent_req(Session *s)
1978 {
1979         static int called = 0;
1980         packet_check_eom();
1981         if (no_agent_forwarding_flag) {
1982                 debug("session_auth_agent_req: no_agent_forwarding_flag");
1983                 return 0;
1984         }
1985         if (called) {
1986                 return 0;
1987         } else {
1988                 called = 1;
1989                 return auth_input_request_forwarding(s->pw);
1990         }
1991 }
1992
1993 int
1994 session_input_channel_req(Channel *c, const char *rtype)
1995 {
1996         int success = 0;
1997         Session *s;
1998
1999         if ((s = session_by_channel(c->self)) == NULL) {
2000                 logit("session_input_channel_req: no session %d req %.100s",
2001                     c->self, rtype);
2002                 return 0;
2003         }
2004         debug("session_input_channel_req: session %d req %s", s->self, rtype);
2005
2006         /*
2007          * a session is in LARVAL state until a shell, a command
2008          * or a subsystem is executed
2009          */
2010         if (c->type == SSH_CHANNEL_LARVAL) {
2011                 if (strcmp(rtype, "shell") == 0) {
2012                         success = session_shell_req(s);
2013                 } else if (strcmp(rtype, "exec") == 0) {
2014                         success = session_exec_req(s);
2015                 } else if (strcmp(rtype, "pty-req") == 0) {
2016                         success =  session_pty_req(s);
2017                 } else if (strcmp(rtype, "x11-req") == 0) {
2018                         success = session_x11_req(s);
2019                 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2020                         success = session_auth_agent_req(s);
2021                 } else if (strcmp(rtype, "subsystem") == 0) {
2022                         success = session_subsystem_req(s);
2023                 } else if (strcmp(rtype, "break") == 0) {
2024                         success = session_break_req(s);
2025                 }
2026         }
2027         if (strcmp(rtype, "window-change") == 0) {
2028                 success = session_window_change_req(s);
2029         }
2030         return success;
2031 }
2032
2033 void
2034 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2035 {
2036         if (!compat20)
2037                 fatal("session_set_fds: called for proto != 2.0");
2038         /*
2039          * now that have a child and a pipe to the child,
2040          * we can activate our channel and register the fd's
2041          */
2042         if (s->chanid == -1)
2043                 fatal("no channel for session %d", s->self);
2044         channel_set_fds(s->chanid,
2045             fdout, fdin, fderr,
2046             fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2047             1,
2048             CHAN_SES_WINDOW_DEFAULT);
2049 }
2050
2051 /*
2052  * Function to perform pty cleanup. Also called if we get aborted abnormally
2053  * (e.g., due to a dropped connection).
2054  */
2055 void
2056 session_pty_cleanup2(void *session)
2057 {
2058         Session *s = session;
2059
2060         if (s == NULL) {
2061                 error("session_pty_cleanup: no session");
2062                 return;
2063         }
2064         if (s->ttyfd == -1)
2065                 return;
2066
2067         debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2068
2069         /* Record that the user has logged out. */
2070         if (s->pid != 0)
2071                 record_logout(s->pid, s->tty, s->pw->pw_name);
2072
2073         /* Release the pseudo-tty. */
2074         if (getuid() == 0)
2075                 pty_release(s->tty);
2076
2077         /*
2078          * Close the server side of the socket pairs.  We must do this after
2079          * the pty cleanup, so that another process doesn't get this pty
2080          * while we're still cleaning up.
2081          */
2082         if (close(s->ptymaster) < 0)
2083                 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2084
2085         /* unlink pty from session */
2086         s->ttyfd = -1;
2087 }
2088
2089 void
2090 session_pty_cleanup(void *session)
2091 {
2092         PRIVSEP(session_pty_cleanup2(session));
2093 }
2094
2095 static char *
2096 sig2name(int sig)
2097 {
2098 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2099         SSH_SIG(ABRT);
2100         SSH_SIG(ALRM);
2101         SSH_SIG(FPE);
2102         SSH_SIG(HUP);
2103         SSH_SIG(ILL);
2104         SSH_SIG(INT);
2105         SSH_SIG(KILL);
2106         SSH_SIG(PIPE);
2107         SSH_SIG(QUIT);
2108         SSH_SIG(SEGV);
2109         SSH_SIG(TERM);
2110         SSH_SIG(USR1);
2111         SSH_SIG(USR2);
2112 #undef  SSH_SIG
2113         return "SIG@openssh.com";
2114 }
2115
2116 static void
2117 session_exit_message(Session *s, int status)
2118 {
2119         Channel *c;
2120
2121         if ((c = channel_lookup(s->chanid)) == NULL)
2122                 fatal("session_exit_message: session %d: no channel %d",
2123                     s->self, s->chanid);
2124         debug("session_exit_message: session %d channel %d pid %ld",
2125             s->self, s->chanid, (long)s->pid);
2126
2127         if (WIFEXITED(status)) {
2128                 channel_request_start(s->chanid, "exit-status", 0);
2129                 packet_put_int(WEXITSTATUS(status));
2130                 packet_send();
2131         } else if (WIFSIGNALED(status)) {
2132                 channel_request_start(s->chanid, "exit-signal", 0);
2133                 packet_put_cstring(sig2name(WTERMSIG(status)));
2134 #ifdef WCOREDUMP
2135                 packet_put_char(WCOREDUMP(status));
2136 #else /* WCOREDUMP */
2137                 packet_put_char(0);
2138 #endif /* WCOREDUMP */
2139                 packet_put_cstring("");
2140                 packet_put_cstring("");
2141                 packet_send();
2142         } else {
2143                 /* Some weird exit cause.  Just exit. */
2144                 packet_disconnect("wait returned status %04x.", status);
2145         }
2146
2147         /* disconnect channel */
2148         debug("session_exit_message: release channel %d", s->chanid);
2149         channel_cancel_cleanup(s->chanid);
2150         /*
2151          * emulate a write failure with 'chan_write_failed', nobody will be
2152          * interested in data we write.
2153          * Note that we must not call 'chan_read_failed', since there could
2154          * be some more data waiting in the pipe.
2155          */
2156         if (c->ostate != CHAN_OUTPUT_CLOSED)
2157                 chan_write_failed(c);
2158         s->chanid = -1;
2159 }
2160
2161 void
2162 session_close(Session *s)
2163 {
2164         debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2165         if (s->ttyfd != -1) {
2166                 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2167                 session_pty_cleanup(s);
2168         }
2169         if (s->term)
2170                 xfree(s->term);
2171         if (s->display)
2172                 xfree(s->display);
2173         if (s->auth_display)
2174                 xfree(s->auth_display);
2175         if (s->auth_data)
2176                 xfree(s->auth_data);
2177         if (s->auth_proto)
2178                 xfree(s->auth_proto);
2179         s->used = 0;
2180         session_proctitle(s);
2181 }
2182
2183 void
2184 session_close_by_pid(pid_t pid, int status)
2185 {
2186         Session *s = session_by_pid(pid);
2187         if (s == NULL) {
2188                 debug("session_close_by_pid: no session for pid %ld",
2189                     (long)pid);
2190                 return;
2191         }
2192         if (s->chanid != -1)
2193                 session_exit_message(s, status);
2194         session_close(s);
2195 }
2196
2197 /*
2198  * this is called when a channel dies before
2199  * the session 'child' itself dies
2200  */
2201 void
2202 session_close_by_channel(int id, void *arg)
2203 {
2204         Session *s = session_by_channel(id);
2205         if (s == NULL) {
2206                 debug("session_close_by_channel: no session for id %d", id);
2207                 return;
2208         }
2209         debug("session_close_by_channel: channel %d child %ld",
2210             id, (long)s->pid);
2211         if (s->pid != 0) {
2212                 debug("session_close_by_channel: channel %d: has child", id);
2213                 /*
2214                  * delay detach of session, but release pty, since
2215                  * the fd's to the child are already closed
2216                  */
2217                 if (s->ttyfd != -1) {
2218                         fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2219                         session_pty_cleanup(s);
2220                 }
2221                 return;
2222         }
2223         /* detach by removing callback */
2224         channel_cancel_cleanup(s->chanid);
2225         s->chanid = -1;
2226         session_close(s);
2227 }
2228
2229 void
2230 session_destroy_all(void (*closefunc)(Session *))
2231 {
2232         int i;
2233         for (i = 0; i < MAX_SESSIONS; i++) {
2234                 Session *s = &sessions[i];
2235                 if (s->used) {
2236                         if (closefunc != NULL)
2237                                 closefunc(s);
2238                         else
2239                                 session_close(s);
2240                 }
2241         }
2242 }
2243
2244 static char *
2245 session_tty_list(void)
2246 {
2247         static char buf[1024];
2248         int i;
2249         char *cp;
2250
2251         buf[0] = '\0';
2252         for (i = 0; i < MAX_SESSIONS; i++) {
2253                 Session *s = &sessions[i];
2254                 if (s->used && s->ttyfd != -1) {
2255                         
2256                         if (strncmp(s->tty, "/dev/", 5) != 0) {
2257                                 cp = strrchr(s->tty, '/');
2258                                 cp = (cp == NULL) ? s->tty : cp + 1;
2259                         } else
2260                                 cp = s->tty + 5;
2261                         
2262                         if (buf[0] != '\0')
2263                                 strlcat(buf, ",", sizeof buf);
2264                         strlcat(buf, cp, sizeof buf);
2265                 }
2266         }
2267         if (buf[0] == '\0')
2268                 strlcpy(buf, "notty", sizeof buf);
2269         return buf;
2270 }
2271
2272 void
2273 session_proctitle(Session *s)
2274 {
2275         if (s->pw == NULL)
2276                 error("no user for session %d", s->self);
2277         else
2278                 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2279 }
2280
2281 int
2282 session_setup_x11fwd(Session *s)
2283 {
2284         struct stat st;
2285         char display[512], auth_display[512];
2286         char hostname[MAXHOSTNAMELEN];
2287
2288         if (no_x11_forwarding_flag) {
2289                 packet_send_debug("X11 forwarding disabled in user configuration file.");
2290                 return 0;
2291         }
2292         if (!options.x11_forwarding) {
2293                 debug("X11 forwarding disabled in server configuration file.");
2294                 return 0;
2295         }
2296         if (!options.xauth_location ||
2297             (stat(options.xauth_location, &st) == -1)) {
2298                 packet_send_debug("No xauth program; cannot forward with spoofing.");
2299                 return 0;
2300         }
2301         if (options.use_login) {
2302                 packet_send_debug("X11 forwarding disabled; "
2303                     "not compatible with UseLogin=yes.");
2304                 return 0;
2305         }
2306         if (s->display != NULL) {
2307                 debug("X11 display already set.");
2308                 return 0;
2309         }
2310         if (x11_create_display_inet(options.x11_display_offset,
2311             options.x11_use_localhost, s->single_connection,
2312             &s->display_number) == -1) {
2313                 debug("x11_create_display_inet failed.");
2314                 return 0;
2315         }
2316
2317         /* Set up a suitable value for the DISPLAY variable. */
2318         if (gethostname(hostname, sizeof(hostname)) < 0)
2319                 fatal("gethostname: %.100s", strerror(errno));
2320         /*
2321          * auth_display must be used as the displayname when the
2322          * authorization entry is added with xauth(1).  This will be
2323          * different than the DISPLAY string for localhost displays.
2324          */
2325         if (options.x11_use_localhost) {
2326                 snprintf(display, sizeof display, "localhost:%u.%u",
2327                     s->display_number, s->screen);
2328                 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2329                     s->display_number, s->screen);
2330                 s->display = xstrdup(display);
2331                 s->auth_display = xstrdup(auth_display);
2332         } else {
2333 #ifdef IPADDR_IN_DISPLAY
2334                 struct hostent *he;
2335                 struct in_addr my_addr;
2336
2337                 he = gethostbyname(hostname);
2338                 if (he == NULL) {
2339                         error("Can't get IP address for X11 DISPLAY.");
2340                         packet_send_debug("Can't get IP address for X11 DISPLAY.");
2341                         return 0;
2342                 }
2343                 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2344                 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2345                     s->display_number, s->screen);
2346 #else
2347                 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2348                     s->display_number, s->screen);
2349 #endif
2350                 s->display = xstrdup(display);
2351                 s->auth_display = xstrdup(display);
2352         }
2353
2354         return 1;
2355 }
2356
2357 static void
2358 do_authenticated2(Authctxt *authctxt)
2359 {
2360         server_loop2(authctxt);
2361 #if defined(GSSAPI)
2362         if (options.gss_cleanup_creds)
2363                 ssh_gssapi_cleanup_creds(NULL);
2364 #endif
2365 }
This page took 0.364745 seconds and 5 git commands to generate.