]> andersk Git - openssh.git/blob - session.c
Stupid djm commits experimental code to head instead of branch
[openssh.git] / session.c
1 /*
2  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
3  *                    All rights reserved
4  *
5  * As far as I am concerned, the code I have written for this software
6  * can be used freely for any purpose.  Any derived versions of this
7  * software must be clearly marked as such, and if the derived work is
8  * incompatible with the protocol description in the RFC file, it must be
9  * called by a name other than "ssh" or "Secure Shell".
10  *
11  * SSH2 support by Markus Friedl.
12  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34
35 #include "includes.h"
36 RCSID("$OpenBSD: session.c,v 1.128 2002/02/16 00:51:44 markus Exp $");
37
38 #include "ssh.h"
39 #include "ssh1.h"
40 #include "ssh2.h"
41 #include "xmalloc.h"
42 #include "sshpty.h"
43 #include "packet.h"
44 #include "buffer.h"
45 #include "mpaux.h"
46 #include "uidswap.h"
47 #include "compat.h"
48 #include "channels.h"
49 #include "bufaux.h"
50 #include "auth.h"
51 #include "auth-options.h"
52 #include "pathnames.h"
53 #include "log.h"
54 #include "servconf.h"
55 #include "sshlogin.h"
56 #include "serverloop.h"
57 #include "canohost.h"
58 #include "session.h"
59
60 #ifdef HAVE_CYGWIN
61 #include <windows.h>
62 #include <sys/cygwin.h>
63 #define is_winnt       (GetVersion() < 0x80000000)
64 #endif
65
66 /* types */
67
68 #define TTYSZ 64
69 typedef struct Session Session;
70 struct Session {
71         int     used;
72         int     self;
73         struct passwd *pw;
74         Authctxt *authctxt;
75         pid_t   pid;
76         /* tty */
77         char    *term;
78         int     ptyfd, ttyfd, ptymaster;
79         int     row, col, xpixel, ypixel;
80         char    tty[TTYSZ];
81         /* X11 */
82         int     display_number;
83         char    *display;
84         int     screen;
85         char    *auth_display;
86         char    *auth_proto;
87         char    *auth_data;
88         int     single_connection;
89         /* proto 2 */
90         int     chanid;
91         int     is_subsystem;
92 };
93
94 /* func */
95
96 Session *session_new(void);
97 void    session_set_fds(Session *, int, int, int);
98 static void     session_pty_cleanup(void *);
99 void    session_proctitle(Session *);
100 int     session_setup_x11fwd(Session *);
101 void    do_exec_pty(Session *, const char *);
102 void    do_exec_no_pty(Session *, const char *);
103 void    do_exec(Session *, const char *);
104 void    do_login(Session *, const char *);
105 #ifdef LOGIN_NEEDS_UTMPX
106 static void     do_pre_login(Session *s);
107 #endif
108 void    do_child(Session *, const char *);
109 void    do_motd(void);
110 int     check_quietlogin(Session *, const char *);
111
112 static void do_authenticated1(Authctxt *);
113 static void do_authenticated2(Authctxt *);
114
115 static void session_close(Session *);
116 static int session_pty_req(Session *);
117
118 /* import */
119 extern ServerOptions options;
120 extern char *__progname;
121 extern int log_stderr;
122 extern int debug_flag;
123 extern u_int utmp_len;
124 extern int startup_pipe;
125 extern void destroy_sensitive_data(void);
126
127 /* original command from peer. */
128 const char *original_command = NULL;
129
130 /* data */
131 #define MAX_SESSIONS 10
132 Session sessions[MAX_SESSIONS];
133
134 #ifdef WITH_AIXAUTHENTICATE
135 char *aixloginmsg;
136 #endif /* WITH_AIXAUTHENTICATE */
137
138 #ifdef HAVE_LOGIN_CAP
139 static login_cap_t *lc;
140 #endif
141
142 void
143 do_authenticated(Authctxt *authctxt)
144 {
145         /*
146          * Cancel the alarm we set to limit the time taken for
147          * authentication.
148          */
149         alarm(0);
150         if (startup_pipe != -1) {
151                 close(startup_pipe);
152                 startup_pipe = -1;
153         }
154 #if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
155         if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
156                 error("unable to get login class");
157                 return;
158         }
159 #ifdef BSD_AUTH
160         if (auth_approval(NULL, lc, authctxt->pw->pw_name, "ssh") <= 0) {
161                 packet_disconnect("Approval failure for %s",
162                     authctxt->pw->pw_name);
163         }
164 #endif
165 #endif
166 #ifdef WITH_AIXAUTHENTICATE
167         /* We don't have a pty yet, so just label the line as "ssh" */
168         if (loginsuccess(authctxt->user,
169             get_canonical_hostname(options.verify_reverse_mapping),
170             "ssh", &aixloginmsg) < 0)
171                 aixloginmsg = NULL;
172 #endif /* WITH_AIXAUTHENTICATE */
173
174         /* setup the channel layer */
175         if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
176                 channel_permit_all_opens();
177
178         if (compat20)
179                 do_authenticated2(authctxt);
180         else
181                 do_authenticated1(authctxt);
182
183         /* remove agent socket */
184         if (auth_get_socket_name())
185                 auth_sock_cleanup_proc(authctxt->pw);
186 #ifdef KRB4
187         if (options.kerberos_ticket_cleanup)
188                 krb4_cleanup_proc(authctxt);
189 #endif
190 #ifdef KRB5
191         if (options.kerberos_ticket_cleanup)
192                 krb5_cleanup_proc(authctxt);
193 #endif
194 }
195
196 /*
197  * Prepares for an interactive session.  This is called after the user has
198  * been successfully authenticated.  During this message exchange, pseudo
199  * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
200  * are requested, etc.
201  */
202 static void
203 do_authenticated1(Authctxt *authctxt)
204 {
205         Session *s;
206         char *command;
207         int success, type, screen_flag;
208         int compression_level = 0, enable_compression_after_reply = 0;
209         u_int proto_len, data_len, dlen;
210
211         s = session_new();
212         s->authctxt = authctxt;
213         s->pw = authctxt->pw;
214
215         /*
216          * We stay in this loop until the client requests to execute a shell
217          * or a command.
218          */
219         for (;;) {
220                 success = 0;
221
222                 /* Get a packet from the client. */
223                 type = packet_read();
224
225                 /* Process the packet. */
226                 switch (type) {
227                 case SSH_CMSG_REQUEST_COMPRESSION:
228                         compression_level = packet_get_int();
229                         packet_check_eom();
230                         if (compression_level < 1 || compression_level > 9) {
231                                 packet_send_debug("Received illegal compression level %d.",
232                                     compression_level);
233                                 break;
234                         }
235                         /* Enable compression after we have responded with SUCCESS. */
236                         enable_compression_after_reply = 1;
237                         success = 1;
238                         break;
239
240                 case SSH_CMSG_REQUEST_PTY:
241                         success = session_pty_req(s);
242                         break;
243
244                 case SSH_CMSG_X11_REQUEST_FORWARDING:
245                         s->auth_proto = packet_get_string(&proto_len);
246                         s->auth_data = packet_get_string(&data_len);
247
248                         screen_flag = packet_get_protocol_flags() &
249                             SSH_PROTOFLAG_SCREEN_NUMBER;
250                         debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
251
252                         if (packet_remaining() == 4) {
253                                 if (!screen_flag)
254                                         debug2("Buggy client: "
255                                             "X11 screen flag missing");
256                                 s->screen = packet_get_int();
257                         } else {
258                                 s->screen = 0;
259                         }
260                         packet_check_eom();
261                         success = session_setup_x11fwd(s);
262                         if (!success) {
263                                 xfree(s->auth_proto);
264                                 xfree(s->auth_data);
265                                 s->auth_proto = NULL;
266                                 s->auth_data = NULL;
267                         }
268                         break;
269
270                 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
271                         if (no_agent_forwarding_flag || compat13) {
272                                 debug("Authentication agent forwarding not permitted for this authentication.");
273                                 break;
274                         }
275                         debug("Received authentication agent forwarding request.");
276                         success = auth_input_request_forwarding(s->pw);
277                         break;
278
279                 case SSH_CMSG_PORT_FORWARD_REQUEST:
280                         if (no_port_forwarding_flag) {
281                                 debug("Port forwarding not permitted for this authentication.");
282                                 break;
283                         }
284                         if (!options.allow_tcp_forwarding) {
285                                 debug("Port forwarding not permitted.");
286                                 break;
287                         }
288                         debug("Received TCP/IP port forwarding request.");
289                         channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
290                         success = 1;
291                         break;
292
293                 case SSH_CMSG_MAX_PACKET_SIZE:
294                         if (packet_set_maxsize(packet_get_int()) > 0)
295                                 success = 1;
296                         break;
297
298 #if defined(AFS) || defined(KRB5)
299                 case SSH_CMSG_HAVE_KERBEROS_TGT:
300                         if (!options.kerberos_tgt_passing) {
301                                 verbose("Kerberos TGT passing disabled.");
302                         } else {
303                                 char *kdata = packet_get_string(&dlen);
304                                 packet_check_eom();
305
306                                 /* XXX - 0x41, see creds_to_radix version */
307                                 if (kdata[0] != 0x41) {
308 #ifdef KRB5
309                                         krb5_data tgt;
310                                         tgt.data = kdata;
311                                         tgt.length = dlen;
312
313                                         if (auth_krb5_tgt(s->authctxt, &tgt))
314                                                 success = 1;
315                                         else
316                                                 verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
317 #endif /* KRB5 */
318                                 } else {
319 #ifdef AFS
320                                         if (auth_krb4_tgt(s->authctxt, kdata))
321                                                 success = 1;
322                                         else
323                                                 verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
324 #endif /* AFS */
325                                 }
326                                 xfree(kdata);
327                         }
328                         break;
329 #endif /* AFS || KRB5 */
330
331 #ifdef AFS
332                 case SSH_CMSG_HAVE_AFS_TOKEN:
333                         if (!options.afs_token_passing || !k_hasafs()) {
334                                 verbose("AFS token passing disabled.");
335                         } else {
336                                 /* Accept AFS token. */
337                                 char *token = packet_get_string(&dlen);
338                                 packet_check_eom();
339
340                                 if (auth_afs_token(s->authctxt, token))
341                                         success = 1;
342                                 else
343                                         verbose("AFS token refused for %.100s",
344                                             s->authctxt->user);
345                                 xfree(token);
346                         }
347                         break;
348 #endif /* AFS */
349
350                 case SSH_CMSG_EXEC_SHELL:
351                 case SSH_CMSG_EXEC_CMD:
352                         if (type == SSH_CMSG_EXEC_CMD) {
353                                 command = packet_get_string(&dlen);
354                                 debug("Exec command '%.500s'", command);
355                                 do_exec(s, command);
356                                 xfree(command);
357                         } else {
358                                 do_exec(s, NULL);
359                         }
360                         packet_check_eom();
361                         session_close(s);
362                         return;
363
364                 default:
365                         /*
366                          * Any unknown messages in this phase are ignored,
367                          * and a failure message is returned.
368                          */
369                         log("Unknown packet type received after authentication: %d", type);
370                 }
371                 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
372                 packet_send();
373                 packet_write_wait();
374
375                 /* Enable compression now that we have replied if appropriate. */
376                 if (enable_compression_after_reply) {
377                         enable_compression_after_reply = 0;
378                         packet_start_compression(compression_level);
379                 }
380         }
381 }
382
383 /*
384  * This is called to fork and execute a command when we have no tty.  This
385  * will call do_child from the child, and server_loop from the parent after
386  * setting up file descriptors and such.
387  */
388 void
389 do_exec_no_pty(Session *s, const char *command)
390 {
391         int pid;
392
393 #ifdef USE_PIPES
394         int pin[2], pout[2], perr[2];
395         /* Allocate pipes for communicating with the program. */
396         if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
397                 packet_disconnect("Could not create pipes: %.100s",
398                                   strerror(errno));
399 #else /* USE_PIPES */
400         int inout[2], err[2];
401         /* Uses socket pairs to communicate with the program. */
402         if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
403             socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
404                 packet_disconnect("Could not create socket pairs: %.100s",
405                                   strerror(errno));
406 #endif /* USE_PIPES */
407         if (s == NULL)
408                 fatal("do_exec_no_pty: no session");
409
410         session_proctitle(s);
411
412 #if defined(USE_PAM)
413         do_pam_session(s->pw->pw_name, NULL);
414         do_pam_setcred(1);
415         if (is_pam_password_change_required())
416                 packet_disconnect("Password change required but no "
417                     "TTY available");
418 #endif /* USE_PAM */
419
420         /* Fork the child. */
421         if ((pid = fork()) == 0) {
422                 /* Child.  Reinitialize the log since the pid has changed. */
423                 log_init(__progname, options.log_level, options.log_facility, log_stderr);
424
425                 /*
426                  * Create a new session and process group since the 4.4BSD
427                  * setlogin() affects the entire process group.
428                  */
429                 if (setsid() < 0)
430                         error("setsid failed: %.100s", strerror(errno));
431
432 #ifdef USE_PIPES
433                 /*
434                  * Redirect stdin.  We close the parent side of the socket
435                  * pair, and make the child side the standard input.
436                  */
437                 close(pin[1]);
438                 if (dup2(pin[0], 0) < 0)
439                         perror("dup2 stdin");
440                 close(pin[0]);
441
442                 /* Redirect stdout. */
443                 close(pout[0]);
444                 if (dup2(pout[1], 1) < 0)
445                         perror("dup2 stdout");
446                 close(pout[1]);
447
448                 /* Redirect stderr. */
449                 close(perr[0]);
450                 if (dup2(perr[1], 2) < 0)
451                         perror("dup2 stderr");
452                 close(perr[1]);
453 #else /* USE_PIPES */
454                 /*
455                  * Redirect stdin, stdout, and stderr.  Stdin and stdout will
456                  * use the same socket, as some programs (particularly rdist)
457                  * seem to depend on it.
458                  */
459                 close(inout[1]);
460                 close(err[1]);
461                 if (dup2(inout[0], 0) < 0)      /* stdin */
462                         perror("dup2 stdin");
463                 if (dup2(inout[0], 1) < 0)      /* stdout.  Note: same socket as stdin. */
464                         perror("dup2 stdout");
465                 if (dup2(err[0], 2) < 0)        /* stderr */
466                         perror("dup2 stderr");
467 #endif /* USE_PIPES */
468
469                 /* Do processing for the child (exec command etc). */
470                 do_child(s, command);
471                 /* NOTREACHED */
472         }
473 #ifdef HAVE_CYGWIN
474         if (is_winnt)
475                 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
476 #endif
477         if (pid < 0)
478                 packet_disconnect("fork failed: %.100s", strerror(errno));
479         s->pid = pid;
480         /* Set interactive/non-interactive mode. */
481         packet_set_interactive(s->display != NULL);
482 #ifdef USE_PIPES
483         /* We are the parent.  Close the child sides of the pipes. */
484         close(pin[0]);
485         close(pout[1]);
486         close(perr[1]);
487
488         if (compat20) {
489                 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
490         } else {
491                 /* Enter the interactive session. */
492                 server_loop(pid, pin[1], pout[0], perr[0]);
493                 /* server_loop has closed pin[1], pout[0], and perr[0]. */
494         }
495 #else /* USE_PIPES */
496         /* We are the parent.  Close the child sides of the socket pairs. */
497         close(inout[0]);
498         close(err[0]);
499
500         /*
501          * Enter the interactive session.  Note: server_loop must be able to
502          * handle the case that fdin and fdout are the same.
503          */
504         if (compat20) {
505                 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
506         } else {
507                 server_loop(pid, inout[1], inout[1], err[1]);
508                 /* server_loop has closed inout[1] and err[1]. */
509         }
510 #endif /* USE_PIPES */
511 }
512
513 /*
514  * This is called to fork and execute a command when we have a tty.  This
515  * will call do_child from the child, and server_loop from the parent after
516  * setting up file descriptors, controlling tty, updating wtmp, utmp,
517  * lastlog, and other such operations.
518  */
519 void
520 do_exec_pty(Session *s, const char *command)
521 {
522         int fdout, ptyfd, ttyfd, ptymaster;
523         pid_t pid;
524
525         if (s == NULL)
526                 fatal("do_exec_pty: no session");
527         ptyfd = s->ptyfd;
528         ttyfd = s->ttyfd;
529
530 #if defined(USE_PAM)
531         do_pam_session(s->pw->pw_name, s->tty);
532         do_pam_setcred(1);
533 #endif
534
535         /* Fork the child. */
536         if ((pid = fork()) == 0) {
537
538                 /* Child.  Reinitialize the log because the pid has changed. */
539                 log_init(__progname, options.log_level, options.log_facility, log_stderr);
540                 /* Close the master side of the pseudo tty. */
541                 close(ptyfd);
542
543                 /* Make the pseudo tty our controlling tty. */
544                 pty_make_controlling_tty(&ttyfd, s->tty);
545
546                 /* Redirect stdin/stdout/stderr from the pseudo tty. */
547                 if (dup2(ttyfd, 0) < 0)
548                         error("dup2 stdin: %s", strerror(errno));
549                 if (dup2(ttyfd, 1) < 0)
550                         error("dup2 stdout: %s", strerror(errno));
551                 if (dup2(ttyfd, 2) < 0)
552                         error("dup2 stderr: %s", strerror(errno));
553
554                 /* Close the extra descriptor for the pseudo tty. */
555                 close(ttyfd);
556
557                 /* record login, etc. similar to login(1) */
558 #ifndef HAVE_OSF_SIA
559                 if (!(options.use_login && command == NULL))
560                         do_login(s, command);
561 # ifdef LOGIN_NEEDS_UTMPX
562                 else
563                         do_pre_login(s);
564 # endif
565 #endif
566
567                 /* Do common processing for the child, such as execing the command. */
568                 do_child(s, command);
569                 /* NOTREACHED */
570         }
571 #ifdef HAVE_CYGWIN
572         if (is_winnt)
573                 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
574 #endif
575         if (pid < 0)
576                 packet_disconnect("fork failed: %.100s", strerror(errno));
577         s->pid = pid;
578
579         /* Parent.  Close the slave side of the pseudo tty. */
580         close(ttyfd);
581
582         /*
583          * Create another descriptor of the pty master side for use as the
584          * standard input.  We could use the original descriptor, but this
585          * simplifies code in server_loop.  The descriptor is bidirectional.
586          */
587         fdout = dup(ptyfd);
588         if (fdout < 0)
589                 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
590
591         /* we keep a reference to the pty master */
592         ptymaster = dup(ptyfd);
593         if (ptymaster < 0)
594                 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
595         s->ptymaster = ptymaster;
596
597         /* Enter interactive session. */
598         packet_set_interactive(1);
599         if (compat20) {
600                 session_set_fds(s, ptyfd, fdout, -1);
601         } else {
602                 server_loop(pid, ptyfd, fdout, -1);
603                 /* server_loop _has_ closed ptyfd and fdout. */
604         }
605 }
606
607 #ifdef LOGIN_NEEDS_UTMPX
608 static void
609 do_pre_login(Session *s)
610 {
611         socklen_t fromlen;
612         struct sockaddr_storage from;
613         pid_t pid = getpid();
614
615         /*
616          * Get IP address of client. If the connection is not a socket, let
617          * the address be 0.0.0.0.
618          */
619         memset(&from, 0, sizeof(from));
620         if (packet_connection_is_on_socket()) {
621                 fromlen = sizeof(from);
622                 if (getpeername(packet_get_connection_in(),
623                     (struct sockaddr *) & from, &fromlen) < 0) {
624                         debug("getpeername: %.100s", strerror(errno));
625                         fatal_cleanup();
626                 }
627         }
628
629         record_utmp_only(pid, s->tty, s->pw->pw_name,
630             get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping),
631             (struct sockaddr *)&from);
632 }
633 #endif
634
635 /*
636  * This is called to fork and execute a command.  If another command is
637  * to be forced, execute that instead.
638  */
639 void
640 do_exec(Session *s, const char *command)
641 {
642         if (forced_command) {
643                 original_command = command;
644                 command = forced_command;
645                 debug("Forced command '%.900s'", command);
646         }
647
648         if (s->ttyfd != -1)
649                 do_exec_pty(s, command);
650         else
651                 do_exec_no_pty(s, command);
652
653         original_command = NULL;
654 }
655
656
657 /* administrative, login(1)-like work */
658 void
659 do_login(Session *s, const char *command)
660 {
661         char *time_string;
662         char hostname[MAXHOSTNAMELEN];
663         socklen_t fromlen;
664         struct sockaddr_storage from;
665         time_t last_login_time;
666         struct passwd * pw = s->pw;
667         pid_t pid = getpid();
668
669         /*
670          * Get IP address of client. If the connection is not a socket, let
671          * the address be 0.0.0.0.
672          */
673         memset(&from, 0, sizeof(from));
674         if (packet_connection_is_on_socket()) {
675                 fromlen = sizeof(from);
676                 if (getpeername(packet_get_connection_in(),
677                     (struct sockaddr *) & from, &fromlen) < 0) {
678                         debug("getpeername: %.100s", strerror(errno));
679                         fatal_cleanup();
680                 }
681         }
682
683         /* Get the time and hostname when the user last logged in. */
684         if (options.print_lastlog) {
685                 hostname[0] = '\0';
686                 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
687                     hostname, sizeof(hostname));
688         }
689
690         /* Record that there was a login on that tty from the remote host. */
691         record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
692             get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping),
693             (struct sockaddr *)&from);
694
695 #ifdef USE_PAM
696         /*
697          * If password change is needed, do it now.
698          * This needs to occur before the ~/.hushlogin check.
699          */
700         if (is_pam_password_change_required()) {
701                 print_pam_messages();
702                 do_pam_chauthtok();
703         }
704 #endif
705
706         if (check_quietlogin(s, command))
707                 return;
708
709 #ifdef USE_PAM
710         if (!is_pam_password_change_required())
711                 print_pam_messages();
712 #endif /* USE_PAM */
713 #ifdef WITH_AIXAUTHENTICATE
714         if (aixloginmsg && *aixloginmsg)
715                 printf("%s\n", aixloginmsg);
716 #endif /* WITH_AIXAUTHENTICATE */
717
718         if (options.print_lastlog && last_login_time != 0) {
719                 time_string = ctime(&last_login_time);
720                 if (strchr(time_string, '\n'))
721                         *strchr(time_string, '\n') = 0;
722                 if (strcmp(hostname, "") == 0)
723                         printf("Last login: %s\r\n", time_string);
724                 else
725                         printf("Last login: %s from %s\r\n", time_string, hostname);
726         }
727
728         do_motd();
729 }
730
731 /*
732  * Display the message of the day.
733  */
734 void
735 do_motd(void)
736 {
737         FILE *f;
738         char buf[256];
739
740         if (options.print_motd) {
741 #ifdef HAVE_LOGIN_CAP
742                 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
743                     "/etc/motd"), "r");
744 #else
745                 f = fopen("/etc/motd", "r");
746 #endif
747                 if (f) {
748                         while (fgets(buf, sizeof(buf), f))
749                                 fputs(buf, stdout);
750                         fclose(f);
751                 }
752         }
753 }
754
755
756 /*
757  * Check for quiet login, either .hushlogin or command given.
758  */
759 int
760 check_quietlogin(Session *s, const char *command)
761 {
762         char buf[256];
763         struct passwd *pw = s->pw;
764         struct stat st;
765
766         /* Return 1 if .hushlogin exists or a command given. */
767         if (command != NULL)
768                 return 1;
769         snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
770 #ifdef HAVE_LOGIN_CAP
771         if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
772                 return 1;
773 #else
774         if (stat(buf, &st) >= 0)
775                 return 1;
776 #endif
777         return 0;
778 }
779
780 /*
781  * Sets the value of the given variable in the environment.  If the variable
782  * already exists, its value is overriden.
783  */
784 static void
785 child_set_env(char ***envp, u_int *envsizep, const char *name,
786         const char *value)
787 {
788         u_int i, namelen;
789         char **env;
790
791         /*
792          * Find the slot where the value should be stored.  If the variable
793          * already exists, we reuse the slot; otherwise we append a new slot
794          * at the end of the array, expanding if necessary.
795          */
796         env = *envp;
797         namelen = strlen(name);
798         for (i = 0; env[i]; i++)
799                 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
800                         break;
801         if (env[i]) {
802                 /* Reuse the slot. */
803                 xfree(env[i]);
804         } else {
805                 /* New variable.  Expand if necessary. */
806                 if (i >= (*envsizep) - 1) {
807                         (*envsizep) += 50;
808                         env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
809                 }
810                 /* Need to set the NULL pointer at end of array beyond the new slot. */
811                 env[i + 1] = NULL;
812         }
813
814         /* Allocate space and format the variable in the appropriate slot. */
815         env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
816         snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
817 }
818
819 /*
820  * Reads environment variables from the given file and adds/overrides them
821  * into the environment.  If the file does not exist, this does nothing.
822  * Otherwise, it must consist of empty lines, comments (line starts with '#')
823  * and assignments of the form name=value.  No other forms are allowed.
824  */
825 static void
826 read_environment_file(char ***env, u_int *envsize,
827         const char *filename)
828 {
829         FILE *f;
830         char buf[4096];
831         char *cp, *value;
832
833         f = fopen(filename, "r");
834         if (!f)
835                 return;
836
837         while (fgets(buf, sizeof(buf), f)) {
838                 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
839                         ;
840                 if (!*cp || *cp == '#' || *cp == '\n')
841                         continue;
842                 if (strchr(cp, '\n'))
843                         *strchr(cp, '\n') = '\0';
844                 value = strchr(cp, '=');
845                 if (value == NULL) {
846                         fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
847                         continue;
848                 }
849                 /*
850                  * Replace the equals sign by nul, and advance value to
851                  * the value string.
852                  */
853                 *value = '\0';
854                 value++;
855                 child_set_env(env, envsize, cp, value);
856         }
857         fclose(f);
858 }
859
860 void copy_environment(char **source, char ***env, u_int *envsize)
861 {
862         char *var_name, *var_val;
863         int i;
864
865         if (source == NULL)
866                 return;
867
868         for(i = 0; source[i] != NULL; i++) {
869                 var_name = xstrdup(source[i]);
870                 if ((var_val = strstr(var_name, "=")) == NULL) {
871                         xfree(var_name);
872                         continue;
873                 }
874                 *var_val++ = '\0';
875
876                 debug3("Copy environment: %s=%s", var_name, var_val);
877                 child_set_env(env, envsize, var_name, var_val);
878                 
879                 xfree(var_name);
880         }
881 }
882
883 static char **
884 do_setup_env(Session *s, const char *shell)
885 {
886         char buf[256];
887         u_int i, envsize;
888         char **env;
889         struct passwd *pw = s->pw;
890
891         /* Initialize the environment. */
892         envsize = 100;
893         env = xmalloc(envsize * sizeof(char *));
894         env[0] = NULL;
895
896 #ifdef HAVE_CYGWIN
897         /*
898          * The Windows environment contains some setting which are
899          * important for a running system. They must not be dropped.
900          */
901         copy_environment(environ, &env, &envsize);
902 #endif
903
904         if (!options.use_login) {
905                 /* Set basic environment. */
906                 child_set_env(&env, &envsize, "USER", pw->pw_name);
907                 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
908                 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
909 #ifdef HAVE_LOGIN_CAP
910                 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
911                 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
912 #else /* HAVE_LOGIN_CAP */
913 # ifndef HAVE_CYGWIN
914                 /*
915                  * There's no standard path on Windows. The path contains
916                  * important components pointing to the system directories,
917                  * needed for loading shared libraries. So the path better
918                  * remains intact here.
919                  */
920                 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
921 # endif /* HAVE_CYGWIN */
922 #endif /* HAVE_LOGIN_CAP */
923
924                 snprintf(buf, sizeof buf, "%.200s/%.50s",
925                          _PATH_MAILDIR, pw->pw_name);
926                 child_set_env(&env, &envsize, "MAIL", buf);
927
928                 /* Normal systems set SHELL by default. */
929                 child_set_env(&env, &envsize, "SHELL", shell);
930         }
931         if (getenv("TZ"))
932                 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
933
934         /* Set custom environment options from RSA authentication. */
935         if (!options.use_login) {
936                 while (custom_environment) {
937                         struct envstring *ce = custom_environment;
938                         char *s = ce->s;
939
940                         for (i = 0; s[i] != '=' && s[i]; i++)
941                                 ;
942                         if (s[i] == '=') {
943                                 s[i] = 0;
944                                 child_set_env(&env, &envsize, s, s + i + 1);
945                         }
946                         custom_environment = ce->next;
947                         xfree(ce->s);
948                         xfree(ce);
949                 }
950         }
951
952         snprintf(buf, sizeof buf, "%.50s %d %d",
953             get_remote_ipaddr(), get_remote_port(), get_local_port());
954         child_set_env(&env, &envsize, "SSH_CLIENT", buf);
955
956         if (s->ttyfd != -1)
957                 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
958         if (s->term)
959                 child_set_env(&env, &envsize, "TERM", s->term);
960         if (s->display)
961                 child_set_env(&env, &envsize, "DISPLAY", s->display);
962         if (original_command)
963                 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
964                     original_command);
965
966 #ifdef _AIX
967         {
968                 char *cp;
969
970                 if ((cp = getenv("AUTHSTATE")) != NULL)
971                         child_set_env(&env, &envsize, "AUTHSTATE", cp);
972                 if ((cp = getenv("KRB5CCNAME")) != NULL)
973                         child_set_env(&env, &envsize, "KRB5CCNAME", cp);
974                 read_environment_file(&env, &envsize, "/etc/environment");
975         }
976 #endif
977 #ifdef KRB4
978         if (s->authctxt->krb4_ticket_file)
979                 child_set_env(&env, &envsize, "KRBTKFILE",
980                     s->authctxt->krb4_ticket_file);
981 #endif
982 #ifdef KRB5
983         if (s->authctxt->krb5_ticket_file)
984                 child_set_env(&env, &envsize, "KRB5CCNAME",
985                     s->authctxt->krb5_ticket_file);
986 #endif
987 #ifdef USE_PAM
988         /* Pull in any environment variables that may have been set by PAM. */
989         copy_environment(fetch_pam_environment(), &env, &envsize);
990 #endif /* USE_PAM */
991
992         if (auth_get_socket_name() != NULL)
993                 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
994                     auth_get_socket_name());
995
996         /* read $HOME/.ssh/environment. */
997         if (!options.use_login) {
998                 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
999                     pw->pw_dir);
1000                 read_environment_file(&env, &envsize, buf);
1001         }
1002         if (debug_flag) {
1003                 /* dump the environment */
1004                 fprintf(stderr, "Environment:\n");
1005                 for (i = 0; env[i]; i++)
1006                         fprintf(stderr, "  %.200s\n", env[i]);
1007         }
1008         return env;
1009 }
1010
1011 /*
1012  * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1013  * first in this order).
1014  */
1015 static void
1016 do_rc_files(Session *s, const char *shell)
1017 {
1018         FILE *f = NULL;
1019         char cmd[1024];
1020         int do_xauth;
1021         struct stat st;
1022
1023         do_xauth =
1024             s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1025
1026         /* ignore _PATH_SSH_USER_RC for subsystems */
1027         if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1028                 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1029                     shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1030                 if (debug_flag)
1031                         fprintf(stderr, "Running %s\n", cmd);
1032                 f = popen(cmd, "w");
1033                 if (f) {
1034                         if (do_xauth)
1035                                 fprintf(f, "%s %s\n", s->auth_proto,
1036                                     s->auth_data);
1037                         pclose(f);
1038                 } else
1039                         fprintf(stderr, "Could not run %s\n",
1040                             _PATH_SSH_USER_RC);
1041         } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1042                 if (debug_flag)
1043                         fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1044                             _PATH_SSH_SYSTEM_RC);
1045                 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1046                 if (f) {
1047                         if (do_xauth)
1048                                 fprintf(f, "%s %s\n", s->auth_proto,
1049                                     s->auth_data);
1050                         pclose(f);
1051                 } else
1052                         fprintf(stderr, "Could not run %s\n",
1053                             _PATH_SSH_SYSTEM_RC);
1054         } else if (do_xauth && options.xauth_location != NULL) {
1055                 /* Add authority data to .Xauthority if appropriate. */
1056                 if (debug_flag) {
1057                         fprintf(stderr,
1058                             "Running %.100s add "
1059                             "%.100s %.100s %.100s\n",
1060                             options.xauth_location, s->auth_display,
1061                             s->auth_proto, s->auth_data);
1062                 }
1063                 snprintf(cmd, sizeof cmd, "%s -q -",
1064                     options.xauth_location);
1065                 f = popen(cmd, "w");
1066                 if (f) {
1067                         fprintf(f, "add %s %s %s\n",
1068                             s->auth_display, s->auth_proto,
1069                             s->auth_data);
1070                         pclose(f);
1071                 } else {
1072                         fprintf(stderr, "Could not run %s\n",
1073                             cmd);
1074                 }
1075         }
1076 }
1077
1078 static void
1079 do_nologin(struct passwd *pw)
1080 {
1081         FILE *f = NULL;
1082         char buf[1024];
1083
1084 #ifdef HAVE_LOGIN_CAP
1085         if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1086                 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1087                     _PATH_NOLOGIN), "r");
1088 #else
1089         if (pw->pw_uid)
1090                 f = fopen(_PATH_NOLOGIN, "r");
1091 #endif
1092         if (f) {
1093                 /* /etc/nologin exists.  Print its contents and exit. */
1094                 while (fgets(buf, sizeof(buf), f))
1095                         fputs(buf, stderr);
1096                 fclose(f);
1097                 exit(254);
1098         }
1099 }
1100
1101 /* Set login name, uid, gid, and groups. */
1102 static void
1103 do_setusercontext(struct passwd *pw)
1104 {
1105 #ifdef HAVE_CYGWIN
1106         if (is_winnt) {
1107 #else /* HAVE_CYGWIN */
1108         if (getuid() == 0 || geteuid() == 0) {
1109 #endif /* HAVE_CYGWIN */
1110 #ifdef HAVE_GETUSERATTR
1111                 set_limits_from_userattr(pw->pw_name);
1112 #endif /* HAVE_GETUSERATTR */
1113 #ifdef HAVE_LOGIN_CAP
1114                 if (setusercontext(lc, pw, pw->pw_uid,
1115                     (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1116                         perror("unable to set user context");
1117                         exit(1);
1118                 }
1119 #else
1120 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1121                 /* Sets login uid for accounting */
1122                 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1123                         error("setluid: %s", strerror(errno));
1124 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1125
1126                 if (setlogin(pw->pw_name) < 0)
1127                         error("setlogin failed: %s", strerror(errno));
1128                 if (setgid(pw->pw_gid) < 0) {
1129                         perror("setgid");
1130                         exit(1);
1131                 }
1132                 /* Initialize the group list. */
1133                 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1134                         perror("initgroups");
1135                         exit(1);
1136                 }
1137                 endgrent();
1138 # ifdef USE_PAM
1139                 /*
1140                  * PAM credentials may take the form of supplementary groups. 
1141                  * These will have been wiped by the above initgroups() call.
1142                  * Reestablish them here.
1143                  */
1144                 do_pam_setcred(0);
1145 # endif /* USE_PAM */
1146 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1147                 irix_setusercontext(pw);
1148 #  endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1149                 /* Permanently switch to the desired uid. */
1150                 permanently_set_uid(pw);
1151 #endif
1152         }
1153         if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1154                 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1155 }
1156
1157 /*
1158  * Performs common processing for the child, such as setting up the
1159  * environment, closing extra file descriptors, setting the user and group
1160  * ids, and executing the command or shell.
1161  */
1162 void
1163 do_child(Session *s, const char *command)
1164 {
1165         extern char **environ;
1166         char **env;
1167         char *argv[10];
1168         const char *shell, *shell0, *hostname = NULL;
1169         struct passwd *pw = s->pw;
1170         u_int i;
1171
1172         /* remove hostkey from the child's memory */
1173         destroy_sensitive_data();
1174
1175         /* login(1) is only called if we execute the login shell */
1176         if (options.use_login && command != NULL)
1177                 options.use_login = 0;
1178
1179         /*
1180          * Login(1) does this as well, and it needs uid 0 for the "-h"
1181          * switch, so we let login(1) to this for us.
1182          */
1183         if (!options.use_login) {
1184 #ifdef HAVE_OSF_SIA
1185                 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
1186                 if (!check_quietlogin(s, command))
1187                         do_motd();
1188 #else /* HAVE_OSF_SIA */
1189                 do_nologin(pw);
1190 # ifdef _AIX
1191                 aix_usrinfo(pw, s->tty, s->ttyfd);
1192 # endif /* _AIX */
1193                 do_setusercontext(pw);
1194 #endif /* HAVE_OSF_SIA */
1195         }
1196
1197         /*
1198          * Get the shell from the password data.  An empty shell field is
1199          * legal, and means /bin/sh.
1200          */
1201         shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1202 #ifdef HAVE_LOGIN_CAP
1203         shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1204 #endif
1205
1206         env = do_setup_env(s, shell);
1207
1208         /* we have to stash the hostname before we close our socket. */
1209         if (options.use_login)
1210                 hostname = get_remote_name_or_ip(utmp_len,
1211                     options.verify_reverse_mapping);
1212         /*
1213          * Close the connection descriptors; note that this is the child, and
1214          * the server will still have the socket open, and it is important
1215          * that we do not shutdown it.  Note that the descriptors cannot be
1216          * closed before building the environment, as we call
1217          * get_remote_ipaddr there.
1218          */
1219         if (packet_get_connection_in() == packet_get_connection_out())
1220                 close(packet_get_connection_in());
1221         else {
1222                 close(packet_get_connection_in());
1223                 close(packet_get_connection_out());
1224         }
1225         /*
1226          * Close all descriptors related to channels.  They will still remain
1227          * open in the parent.
1228          */
1229         /* XXX better use close-on-exec? -markus */
1230         channel_close_all();
1231
1232         /*
1233          * Close any extra file descriptors.  Note that there may still be
1234          * descriptors left by system functions.  They will be closed later.
1235          */
1236         endpwent();
1237
1238         /*
1239          * Close any extra open file descriptors so that we don\'t have them
1240          * hanging around in clients.  Note that we want to do this after
1241          * initgroups, because at least on Solaris 2.3 it leaves file
1242          * descriptors open.
1243          */
1244         for (i = 3; i < 64; i++)
1245                 close(i);
1246
1247         /*
1248          * Must take new environment into use so that .ssh/rc,
1249          * /etc/ssh/sshrc and xauth are run in the proper environment.
1250          */
1251         environ = env;
1252
1253 #ifdef AFS
1254         /* Try to get AFS tokens for the local cell. */
1255         if (k_hasafs()) {
1256                 char cell[64];
1257
1258                 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1259                         krb_afslog(cell, 0);
1260
1261                 krb_afslog(0, 0);
1262         }
1263 #endif /* AFS */
1264
1265         /* Change current directory to the user\'s home directory. */
1266         if (chdir(pw->pw_dir) < 0) {
1267                 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1268                     pw->pw_dir, strerror(errno));
1269 #ifdef HAVE_LOGIN_CAP
1270                 if (login_getcapbool(lc, "requirehome", 0))
1271                         exit(1);
1272 #endif
1273         }
1274
1275         if (!options.use_login)
1276                 do_rc_files(s, shell);
1277
1278         /* restore SIGPIPE for child */
1279         signal(SIGPIPE,  SIG_DFL);
1280
1281         if (options.use_login) {
1282                 /* Launch login(1). */
1283
1284                 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1285 #ifdef LOGIN_NEEDS_TERM
1286                     (s->term ? s->term : "unknown"),
1287 #endif /* LOGIN_NEEDS_TERM */
1288                     "-p", "-f", "--", pw->pw_name, (char *)NULL);
1289
1290                 /* Login couldn't be executed, die. */
1291
1292                 perror("login");
1293                 exit(1);
1294         }
1295
1296         /* Get the last component of the shell name. */
1297         if ((shell0 = strrchr(shell, '/')) != NULL)
1298                 shell0++;
1299         else
1300                 shell0 = shell;
1301
1302         /*
1303          * If we have no command, execute the shell.  In this case, the shell
1304          * name to be passed in argv[0] is preceded by '-' to indicate that
1305          * this is a login shell.
1306          */
1307         if (!command) {
1308                 char argv0[256];
1309
1310                 /* Start the shell.  Set initial character to '-'. */
1311                 argv0[0] = '-';
1312
1313                 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1314                     >= sizeof(argv0) - 1) {
1315                         errno = EINVAL;
1316                         perror(shell);
1317                         exit(1);
1318                 }
1319
1320                 /* Execute the shell. */
1321                 argv[0] = argv0;
1322                 argv[1] = NULL;
1323                 execve(shell, argv, env);
1324
1325                 /* Executing the shell failed. */
1326                 perror(shell);
1327                 exit(1);
1328         }
1329         /*
1330          * Execute the command using the user's shell.  This uses the -c
1331          * option to execute the command.
1332          */
1333         argv[0] = (char *) shell0;
1334         argv[1] = "-c";
1335         argv[2] = (char *) command;
1336         argv[3] = NULL;
1337         execve(shell, argv, env);
1338         perror(shell);
1339         exit(1);
1340 }
1341
1342 Session *
1343 session_new(void)
1344 {
1345         int i;
1346         static int did_init = 0;
1347         if (!did_init) {
1348                 debug("session_new: init");
1349                 for (i = 0; i < MAX_SESSIONS; i++) {
1350                         sessions[i].used = 0;
1351                 }
1352                 did_init = 1;
1353         }
1354         for (i = 0; i < MAX_SESSIONS; i++) {
1355                 Session *s = &sessions[i];
1356                 if (! s->used) {
1357                         memset(s, 0, sizeof(*s));
1358                         s->chanid = -1;
1359                         s->ptyfd = -1;
1360                         s->ttyfd = -1;
1361                         s->used = 1;
1362                         s->self = i;
1363                         debug("session_new: session %d", i);
1364                         return s;
1365                 }
1366         }
1367         return NULL;
1368 }
1369
1370 static void
1371 session_dump(void)
1372 {
1373         int i;
1374         for (i = 0; i < MAX_SESSIONS; i++) {
1375                 Session *s = &sessions[i];
1376                 debug("dump: used %d session %d %p channel %d pid %d",
1377                     s->used,
1378                     s->self,
1379                     s,
1380                     s->chanid,
1381                     s->pid);
1382         }
1383 }
1384
1385 int
1386 session_open(Authctxt *authctxt, int chanid)
1387 {
1388         Session *s = session_new();
1389         debug("session_open: channel %d", chanid);
1390         if (s == NULL) {
1391                 error("no more sessions");
1392                 return 0;
1393         }
1394         s->authctxt = authctxt;
1395         s->pw = authctxt->pw;
1396         if (s->pw == NULL)
1397                 fatal("no user for session %d", s->self);
1398         debug("session_open: session %d: link with channel %d", s->self, chanid);
1399         s->chanid = chanid;
1400         return 1;
1401 }
1402
1403 static Session *
1404 session_by_channel(int id)
1405 {
1406         int i;
1407         for (i = 0; i < MAX_SESSIONS; i++) {
1408                 Session *s = &sessions[i];
1409                 if (s->used && s->chanid == id) {
1410                         debug("session_by_channel: session %d channel %d", i, id);
1411                         return s;
1412                 }
1413         }
1414         debug("session_by_channel: unknown channel %d", id);
1415         session_dump();
1416         return NULL;
1417 }
1418
1419 static Session *
1420 session_by_pid(pid_t pid)
1421 {
1422         int i;
1423         debug("session_by_pid: pid %d", pid);
1424         for (i = 0; i < MAX_SESSIONS; i++) {
1425                 Session *s = &sessions[i];
1426                 if (s->used && s->pid == pid)
1427                         return s;
1428         }
1429         error("session_by_pid: unknown pid %d", pid);
1430         session_dump();
1431         return NULL;
1432 }
1433
1434 static int
1435 session_window_change_req(Session *s)
1436 {
1437         s->col = packet_get_int();
1438         s->row = packet_get_int();
1439         s->xpixel = packet_get_int();
1440         s->ypixel = packet_get_int();
1441         packet_check_eom();
1442         pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1443         return 1;
1444 }
1445
1446 static int
1447 session_pty_req(Session *s)
1448 {
1449         u_int len;
1450         int n_bytes;
1451
1452         if (no_pty_flag) {
1453                 debug("Allocating a pty not permitted for this authentication.");
1454                 return 0;
1455         }
1456         if (s->ttyfd != -1) {
1457                 packet_disconnect("Protocol error: you already have a pty.");
1458                 return 0;
1459         }
1460
1461         s->term = packet_get_string(&len);
1462
1463         if (compat20) {
1464                 s->col = packet_get_int();
1465                 s->row = packet_get_int();
1466         } else {
1467                 s->row = packet_get_int();
1468                 s->col = packet_get_int();
1469         }
1470         s->xpixel = packet_get_int();
1471         s->ypixel = packet_get_int();
1472
1473         if (strcmp(s->term, "") == 0) {
1474                 xfree(s->term);
1475                 s->term = NULL;
1476         }
1477
1478         /* Allocate a pty and open it. */
1479         debug("Allocating pty.");
1480         if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1481                 if (s->term)
1482                         xfree(s->term);
1483                 s->term = NULL;
1484                 s->ptyfd = -1;
1485                 s->ttyfd = -1;
1486                 error("session_pty_req: session %d alloc failed", s->self);
1487                 return 0;
1488         }
1489         debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1490
1491         /* for SSH1 the tty modes length is not given */
1492         if (!compat20)
1493                 n_bytes = packet_remaining();
1494         tty_parse_modes(s->ttyfd, &n_bytes);
1495
1496         /*
1497          * Add a cleanup function to clear the utmp entry and record logout
1498          * time in case we call fatal() (e.g., the connection gets closed).
1499          */
1500         fatal_add_cleanup(session_pty_cleanup, (void *)s);
1501         pty_setowner(s->pw, s->tty);
1502
1503         /* Set window size from the packet. */
1504         pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1505
1506         packet_check_eom();
1507         session_proctitle(s);
1508         return 1;
1509 }
1510
1511 static int
1512 session_subsystem_req(Session *s)
1513 {
1514         struct stat st;
1515         u_int len;
1516         int success = 0;
1517         char *cmd, *subsys = packet_get_string(&len);
1518         int i;
1519
1520         packet_check_eom();
1521         log("subsystem request for %.100s", subsys);
1522
1523         for (i = 0; i < options.num_subsystems; i++) {
1524                 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1525                         cmd = options.subsystem_command[i];
1526                         if (stat(cmd, &st) < 0) {
1527                                 error("subsystem: cannot stat %s: %s", cmd,
1528                                     strerror(errno));
1529                                 break;
1530                         }
1531                         debug("subsystem: exec() %s", cmd);
1532                         s->is_subsystem = 1;
1533                         do_exec(s, cmd);
1534                         success = 1;
1535                         break;
1536                 }
1537         }
1538
1539         if (!success)
1540                 log("subsystem request for %.100s failed, subsystem not found",
1541                     subsys);
1542
1543         xfree(subsys);
1544         return success;
1545 }
1546
1547 static int
1548 session_x11_req(Session *s)
1549 {
1550         int success;
1551
1552         s->single_connection = packet_get_char();
1553         s->auth_proto = packet_get_string(NULL);
1554         s->auth_data = packet_get_string(NULL);
1555         s->screen = packet_get_int();
1556         packet_check_eom();
1557
1558         success = session_setup_x11fwd(s);
1559         if (!success) {
1560                 xfree(s->auth_proto);
1561                 xfree(s->auth_data);
1562                 s->auth_proto = NULL;
1563                 s->auth_data = NULL;
1564         }
1565         return success;
1566 }
1567
1568 static int
1569 session_shell_req(Session *s)
1570 {
1571         packet_check_eom();
1572         do_exec(s, NULL);
1573         return 1;
1574 }
1575
1576 static int
1577 session_exec_req(Session *s)
1578 {
1579         u_int len;
1580         char *command = packet_get_string(&len);
1581         packet_check_eom();
1582         do_exec(s, command);
1583         xfree(command);
1584         return 1;
1585 }
1586
1587 static int
1588 session_auth_agent_req(Session *s)
1589 {
1590         static int called = 0;
1591         packet_check_eom();
1592         if (no_agent_forwarding_flag) {
1593                 debug("session_auth_agent_req: no_agent_forwarding_flag");
1594                 return 0;
1595         }
1596         if (called) {
1597                 return 0;
1598         } else {
1599                 called = 1;
1600                 return auth_input_request_forwarding(s->pw);
1601         }
1602 }
1603
1604 int
1605 session_input_channel_req(Channel *c, const char *rtype)
1606 {
1607         int success = 0;
1608         Session *s;
1609
1610         if ((s = session_by_channel(c->self)) == NULL) {
1611                 log("session_input_channel_req: no session %d req %.100s",
1612                     c->self, rtype);
1613                 return 0;
1614         }
1615         debug("session_input_channel_req: session %d req %s", s->self, rtype);
1616
1617         /*
1618          * a session is in LARVAL state until a shell, a command
1619          * or a subsystem is executed
1620          */
1621         if (c->type == SSH_CHANNEL_LARVAL) {
1622                 if (strcmp(rtype, "shell") == 0) {
1623                         success = session_shell_req(s);
1624                 } else if (strcmp(rtype, "exec") == 0) {
1625                         success = session_exec_req(s);
1626                 } else if (strcmp(rtype, "pty-req") == 0) {
1627                         success =  session_pty_req(s);
1628                 } else if (strcmp(rtype, "x11-req") == 0) {
1629                         success = session_x11_req(s);
1630                 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1631                         success = session_auth_agent_req(s);
1632                 } else if (strcmp(rtype, "subsystem") == 0) {
1633                         success = session_subsystem_req(s);
1634                 }
1635         }
1636         if (strcmp(rtype, "window-change") == 0) {
1637                 success = session_window_change_req(s);
1638         }
1639         return success;
1640 }
1641
1642 void
1643 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1644 {
1645         if (!compat20)
1646                 fatal("session_set_fds: called for proto != 2.0");
1647         /*
1648          * now that have a child and a pipe to the child,
1649          * we can activate our channel and register the fd's
1650          */
1651         if (s->chanid == -1)
1652                 fatal("no channel for session %d", s->self);
1653         channel_set_fds(s->chanid,
1654             fdout, fdin, fderr,
1655             fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1656             1,
1657             CHAN_SES_WINDOW_DEFAULT);
1658 }
1659
1660 /*
1661  * Function to perform pty cleanup. Also called if we get aborted abnormally
1662  * (e.g., due to a dropped connection).
1663  */
1664 static void
1665 session_pty_cleanup(void *session)
1666 {
1667         Session *s = session;
1668
1669         if (s == NULL) {
1670                 error("session_pty_cleanup: no session");
1671                 return;
1672         }
1673         if (s->ttyfd == -1)
1674                 return;
1675
1676         debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1677
1678         /* Record that the user has logged out. */
1679         if (s->pid != 0)
1680                 record_logout(s->pid, s->tty, s->pw->pw_name);
1681
1682         /* Release the pseudo-tty. */
1683         pty_release(s->tty);
1684
1685         /*
1686          * Close the server side of the socket pairs.  We must do this after
1687          * the pty cleanup, so that another process doesn't get this pty
1688          * while we're still cleaning up.
1689          */
1690         if (close(s->ptymaster) < 0)
1691                 error("close(s->ptymaster): %s", strerror(errno));
1692
1693         /* unlink pty from session */
1694         s->ttyfd = -1;
1695 }
1696
1697 static void
1698 session_exit_message(Session *s, int status)
1699 {
1700         Channel *c;
1701
1702         if ((c = channel_lookup(s->chanid)) == NULL)
1703                 fatal("session_exit_message: session %d: no channel %d",
1704                     s->self, s->chanid);
1705         debug("session_exit_message: session %d channel %d pid %d",
1706             s->self, s->chanid, s->pid);
1707
1708         if (WIFEXITED(status)) {
1709                 channel_request_start(s->chanid, "exit-status", 0);
1710                 packet_put_int(WEXITSTATUS(status));
1711                 packet_send();
1712         } else if (WIFSIGNALED(status)) {
1713                 channel_request_start(s->chanid, "exit-signal", 0);
1714                 packet_put_int(WTERMSIG(status));
1715 #ifdef WCOREDUMP
1716                 packet_put_char(WCOREDUMP(status));
1717 #else /* WCOREDUMP */
1718                 packet_put_char(0);
1719 #endif /* WCOREDUMP */
1720                 packet_put_cstring("");
1721                 packet_put_cstring("");
1722                 packet_send();
1723         } else {
1724                 /* Some weird exit cause.  Just exit. */
1725                 packet_disconnect("wait returned status %04x.", status);
1726         }
1727
1728         /* disconnect channel */
1729         debug("session_exit_message: release channel %d", s->chanid);
1730         channel_cancel_cleanup(s->chanid);
1731         /*
1732          * emulate a write failure with 'chan_write_failed', nobody will be
1733          * interested in data we write.
1734          * Note that we must not call 'chan_read_failed', since there could
1735          * be some more data waiting in the pipe.
1736          */
1737         if (c->ostate != CHAN_OUTPUT_CLOSED)
1738                 chan_write_failed(c);
1739         s->chanid = -1;
1740 }
1741
1742 static void
1743 session_close(Session *s)
1744 {
1745         debug("session_close: session %d pid %d", s->self, s->pid);
1746         if (s->ttyfd != -1) {
1747                 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1748                 session_pty_cleanup(s);
1749         }
1750         if (s->term)
1751                 xfree(s->term);
1752         if (s->display)
1753                 xfree(s->display);
1754         if (s->auth_display)
1755                 xfree(s->auth_display);
1756         if (s->auth_data)
1757                 xfree(s->auth_data);
1758         if (s->auth_proto)
1759                 xfree(s->auth_proto);
1760         s->used = 0;
1761         session_proctitle(s);
1762 }
1763
1764 void
1765 session_close_by_pid(pid_t pid, int status)
1766 {
1767         Session *s = session_by_pid(pid);
1768         if (s == NULL) {
1769                 debug("session_close_by_pid: no session for pid %d", pid);
1770                 return;
1771         }
1772         if (s->chanid != -1)
1773                 session_exit_message(s, status);
1774         session_close(s);
1775 }
1776
1777 /*
1778  * this is called when a channel dies before
1779  * the session 'child' itself dies
1780  */
1781 void
1782 session_close_by_channel(int id, void *arg)
1783 {
1784         Session *s = session_by_channel(id);
1785         if (s == NULL) {
1786                 debug("session_close_by_channel: no session for id %d", id);
1787                 return;
1788         }
1789         debug("session_close_by_channel: channel %d child %d", id, s->pid);
1790         if (s->pid != 0) {
1791                 debug("session_close_by_channel: channel %d: has child", id);
1792                 /*
1793                  * delay detach of session, but release pty, since
1794                  * the fd's to the child are already closed
1795                  */
1796                 if (s->ttyfd != -1) {
1797                         fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1798                         session_pty_cleanup(s);
1799                 }
1800                 return;
1801         }
1802         /* detach by removing callback */
1803         channel_cancel_cleanup(s->chanid);
1804         s->chanid = -1;
1805         session_close(s);
1806 }
1807
1808 void
1809 session_destroy_all(void)
1810 {
1811         int i;
1812         for (i = 0; i < MAX_SESSIONS; i++) {
1813                 Session *s = &sessions[i];
1814                 if (s->used)
1815                         session_close(s);
1816         }
1817 }
1818
1819 static char *
1820 session_tty_list(void)
1821 {
1822         static char buf[1024];
1823         int i;
1824         buf[0] = '\0';
1825         for (i = 0; i < MAX_SESSIONS; i++) {
1826                 Session *s = &sessions[i];
1827                 if (s->used && s->ttyfd != -1) {
1828                         if (buf[0] != '\0')
1829                                 strlcat(buf, ",", sizeof buf);
1830                         strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1831                 }
1832         }
1833         if (buf[0] == '\0')
1834                 strlcpy(buf, "notty", sizeof buf);
1835         return buf;
1836 }
1837
1838 void
1839 session_proctitle(Session *s)
1840 {
1841         if (s->pw == NULL)
1842                 error("no user for session %d", s->self);
1843         else
1844                 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1845 }
1846
1847 int
1848 session_setup_x11fwd(Session *s)
1849 {
1850         struct stat st;
1851         char display[512], auth_display[512];
1852         char hostname[MAXHOSTNAMELEN];
1853
1854         if (no_x11_forwarding_flag) {
1855                 packet_send_debug("X11 forwarding disabled in user configuration file.");
1856                 return 0;
1857         }
1858         if (!options.x11_forwarding) {
1859                 debug("X11 forwarding disabled in server configuration file.");
1860                 return 0;
1861         }
1862         if (!options.xauth_location ||
1863             (stat(options.xauth_location, &st) == -1)) {
1864                 packet_send_debug("No xauth program; cannot forward with spoofing.");
1865                 return 0;
1866         }
1867         if (options.use_login) {
1868                 packet_send_debug("X11 forwarding disabled; "
1869                     "not compatible with UseLogin=yes.");
1870                 return 0;
1871         }
1872         if (s->display != NULL) {
1873                 debug("X11 display already set.");
1874                 return 0;
1875         }
1876         s->display_number = x11_create_display_inet(options.x11_display_offset,
1877             options.x11_use_localhost, s->single_connection);
1878         if (s->display_number == -1) {
1879                 debug("x11_create_display_inet failed.");
1880                 return 0;
1881         }
1882
1883         /* Set up a suitable value for the DISPLAY variable. */
1884         if (gethostname(hostname, sizeof(hostname)) < 0)
1885                 fatal("gethostname: %.100s", strerror(errno));
1886         /*
1887          * auth_display must be used as the displayname when the
1888          * authorization entry is added with xauth(1).  This will be
1889          * different than the DISPLAY string for localhost displays.
1890          */
1891         if (options.x11_use_localhost) {
1892                 snprintf(display, sizeof display, "localhost:%d.%d",
1893                     s->display_number, s->screen);
1894                 snprintf(auth_display, sizeof auth_display, "unix:%d.%d",
1895                     s->display_number, s->screen);
1896                 s->display = xstrdup(display);
1897                 s->auth_display = xstrdup(auth_display);
1898         } else {
1899 #ifdef IPADDR_IN_DISPLAY
1900                 struct hostent *he;
1901                 struct in_addr my_addr;
1902
1903                 he = gethostbyname(hostname);
1904                 if (he == NULL) {
1905                         error("Can't get IP address for X11 DISPLAY.");
1906                         packet_send_debug("Can't get IP address for X11 DISPLAY.");
1907                         return 0;
1908                 }
1909                 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
1910                 snprintf(display, sizeof display, "%.50s:%d.%d", inet_ntoa(my_addr),
1911                     s->display_number, s->screen);
1912 #else
1913                 snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
1914                     s->display_number, s->screen);
1915 #endif
1916                 s->display = xstrdup(display);
1917                 s->auth_display = xstrdup(display);
1918         }
1919
1920         return 1;
1921 }
1922
1923 static void
1924 do_authenticated2(Authctxt *authctxt)
1925 {
1926         server_loop2(authctxt);
1927 }
This page took 0.198067 seconds and 5 git commands to generate.