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