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