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