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