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