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