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