- (djm) OpenBSD CVS Sync
[openssh-git.git] / session.c
blob057298c868cd726374f8325a899bfaf2cfd22363
1 /* $OpenBSD: session.c,v 1.218 2006/08/18 09:15:20 markus Exp $ */
2 /*
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4 * All rights reserved
6 * As far as I am concerned, the code I have written for this software
7 * can be used freely for any purpose. Any derived versions of this
8 * software must be clearly marked as such, and if the derived work is
9 * incompatible with the protocol description in the RFC file, it must be
10 * called by a name other than "ssh" or "Secure Shell".
12 * SSH2 support by Markus Friedl.
13 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
17 * are met:
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
24 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 #include "includes.h"
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #ifdef HAVE_SYS_STAT_H
41 # include <sys/stat.h>
42 #endif
43 #include <sys/socket.h>
44 #include <sys/un.h>
45 #include <sys/wait.h>
47 #include <arpa/inet.h>
49 #include <errno.h>
50 #include <grp.h>
51 #ifdef HAVE_PATHS_H
52 #include <paths.h>
53 #endif
54 #include <pwd.h>
55 #include <signal.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
61 #include "xmalloc.h"
62 #include "ssh.h"
63 #include "ssh1.h"
64 #include "ssh2.h"
65 #include "sshpty.h"
66 #include "packet.h"
67 #include "buffer.h"
68 #include "match.h"
69 #include "uidswap.h"
70 #include "compat.h"
71 #include "channels.h"
72 #include "key.h"
73 #include "cipher.h"
74 #ifdef GSSAPI
75 #include "ssh-gss.h"
76 #endif
77 #include "hostfile.h"
78 #include "auth.h"
79 #include "auth-options.h"
80 #include "pathnames.h"
81 #include "log.h"
82 #include "servconf.h"
83 #include "sshlogin.h"
84 #include "serverloop.h"
85 #include "canohost.h"
86 #include "session.h"
87 #include "kex.h"
88 #include "monitor_wrap.h"
90 #if defined(KRB5) && defined(USE_AFS)
91 #include <kafs.h>
92 #endif
94 /* func */
96 Session *session_new(void);
97 void session_set_fds(Session *, int, int, int);
98 void session_pty_cleanup(Session *);
99 void session_proctitle(Session *);
100 int session_setup_x11fwd(Session *);
101 void do_exec_pty(Session *, const char *);
102 void do_exec_no_pty(Session *, const char *);
103 void do_exec(Session *, const char *);
104 void do_login(Session *, const char *);
105 #ifdef LOGIN_NEEDS_UTMPX
106 static void do_pre_login(Session *s);
107 #endif
108 void do_child(Session *, const char *);
109 void do_motd(void);
110 int check_quietlogin(Session *, const char *);
112 static void do_authenticated1(Authctxt *);
113 static void do_authenticated2(Authctxt *);
115 static int session_pty_req(Session *);
117 /* import */
118 extern ServerOptions options;
119 extern char *__progname;
120 extern int log_stderr;
121 extern int debug_flag;
122 extern u_int utmp_len;
123 extern int startup_pipe;
124 extern void destroy_sensitive_data(void);
125 extern Buffer loginmsg;
127 /* original command from peer. */
128 const char *original_command = NULL;
130 /* data */
131 #define MAX_SESSIONS 10
132 Session sessions[MAX_SESSIONS];
134 #ifdef HAVE_LOGIN_CAP
135 login_cap_t *lc;
136 #endif
138 static int is_child = 0;
140 /* Name and directory of socket for authentication agent forwarding. */
141 static char *auth_sock_name = NULL;
142 static char *auth_sock_dir = NULL;
144 /* removes the agent forwarding socket */
146 static void
147 auth_sock_cleanup_proc(struct passwd *pw)
149 if (auth_sock_name != NULL) {
150 temporarily_use_uid(pw);
151 unlink(auth_sock_name);
152 rmdir(auth_sock_dir);
153 auth_sock_name = NULL;
154 restore_uid();
158 static int
159 auth_input_request_forwarding(struct passwd * pw)
161 Channel *nc;
162 int sock;
163 struct sockaddr_un sunaddr;
165 if (auth_sock_name != NULL) {
166 error("authentication forwarding requested twice.");
167 return 0;
170 /* Temporarily drop privileged uid for mkdir/bind. */
171 temporarily_use_uid(pw);
173 /* Allocate a buffer for the socket name, and format the name. */
174 auth_sock_name = xmalloc(MAXPATHLEN);
175 auth_sock_dir = xmalloc(MAXPATHLEN);
176 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
178 /* Create private directory for socket */
179 if (mkdtemp(auth_sock_dir) == NULL) {
180 packet_send_debug("Agent forwarding disabled: "
181 "mkdtemp() failed: %.100s", strerror(errno));
182 restore_uid();
183 xfree(auth_sock_name);
184 xfree(auth_sock_dir);
185 auth_sock_name = NULL;
186 auth_sock_dir = NULL;
187 return 0;
189 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
190 auth_sock_dir, (long) getpid());
192 /* Create the socket. */
193 sock = socket(AF_UNIX, SOCK_STREAM, 0);
194 if (sock < 0)
195 packet_disconnect("socket: %.100s", strerror(errno));
197 /* Bind it to the name. */
198 memset(&sunaddr, 0, sizeof(sunaddr));
199 sunaddr.sun_family = AF_UNIX;
200 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
202 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0)
203 packet_disconnect("bind: %.100s", strerror(errno));
205 /* Restore the privileged uid. */
206 restore_uid();
208 /* Start listening on the socket. */
209 if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
210 packet_disconnect("listen: %.100s", strerror(errno));
212 /* Allocate a channel for the authentication agent socket. */
213 nc = channel_new("auth socket",
214 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
215 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
216 0, "auth socket", 1);
217 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
218 return 1;
221 static void
222 display_loginmsg(void)
224 if (buffer_len(&loginmsg) > 0) {
225 buffer_append(&loginmsg, "\0", 1);
226 printf("%s", (char *)buffer_ptr(&loginmsg));
227 buffer_clear(&loginmsg);
231 void
232 do_authenticated(Authctxt *authctxt)
234 setproctitle("%s", authctxt->pw->pw_name);
236 /* setup the channel layer */
237 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
238 channel_permit_all_opens();
240 if (compat20)
241 do_authenticated2(authctxt);
242 else
243 do_authenticated1(authctxt);
245 do_cleanup(authctxt);
249 * Prepares for an interactive session. This is called after the user has
250 * been successfully authenticated. During this message exchange, pseudo
251 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
252 * are requested, etc.
254 static void
255 do_authenticated1(Authctxt *authctxt)
257 Session *s;
258 char *command;
259 int success, type, screen_flag;
260 int enable_compression_after_reply = 0;
261 u_int proto_len, data_len, dlen, compression_level = 0;
263 s = session_new();
264 if (s == NULL) {
265 error("no more sessions");
266 return;
268 s->authctxt = authctxt;
269 s->pw = authctxt->pw;
272 * We stay in this loop until the client requests to execute a shell
273 * or a command.
275 for (;;) {
276 success = 0;
278 /* Get a packet from the client. */
279 type = packet_read();
281 /* Process the packet. */
282 switch (type) {
283 case SSH_CMSG_REQUEST_COMPRESSION:
284 compression_level = packet_get_int();
285 packet_check_eom();
286 if (compression_level < 1 || compression_level > 9) {
287 packet_send_debug("Received invalid compression level %d.",
288 compression_level);
289 break;
291 if (options.compression == COMP_NONE) {
292 debug2("compression disabled");
293 break;
295 /* Enable compression after we have responded with SUCCESS. */
296 enable_compression_after_reply = 1;
297 success = 1;
298 break;
300 case SSH_CMSG_REQUEST_PTY:
301 success = session_pty_req(s);
302 break;
304 case SSH_CMSG_X11_REQUEST_FORWARDING:
305 s->auth_proto = packet_get_string(&proto_len);
306 s->auth_data = packet_get_string(&data_len);
308 screen_flag = packet_get_protocol_flags() &
309 SSH_PROTOFLAG_SCREEN_NUMBER;
310 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
312 if (packet_remaining() == 4) {
313 if (!screen_flag)
314 debug2("Buggy client: "
315 "X11 screen flag missing");
316 s->screen = packet_get_int();
317 } else {
318 s->screen = 0;
320 packet_check_eom();
321 success = session_setup_x11fwd(s);
322 if (!success) {
323 xfree(s->auth_proto);
324 xfree(s->auth_data);
325 s->auth_proto = NULL;
326 s->auth_data = NULL;
328 break;
330 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
331 if (no_agent_forwarding_flag || compat13) {
332 debug("Authentication agent forwarding not permitted for this authentication.");
333 break;
335 debug("Received authentication agent forwarding request.");
336 success = auth_input_request_forwarding(s->pw);
337 break;
339 case SSH_CMSG_PORT_FORWARD_REQUEST:
340 if (no_port_forwarding_flag) {
341 debug("Port forwarding not permitted for this authentication.");
342 break;
344 if (!options.allow_tcp_forwarding) {
345 debug("Port forwarding not permitted.");
346 break;
348 debug("Received TCP/IP port forwarding request.");
349 if (channel_input_port_forward_request(s->pw->pw_uid == 0,
350 options.gateway_ports) < 0) {
351 debug("Port forwarding failed.");
352 break;
354 success = 1;
355 break;
357 case SSH_CMSG_MAX_PACKET_SIZE:
358 if (packet_set_maxsize(packet_get_int()) > 0)
359 success = 1;
360 break;
362 case SSH_CMSG_EXEC_SHELL:
363 case SSH_CMSG_EXEC_CMD:
364 if (type == SSH_CMSG_EXEC_CMD) {
365 command = packet_get_string(&dlen);
366 debug("Exec command '%.500s'", command);
367 do_exec(s, command);
368 xfree(command);
369 } else {
370 do_exec(s, NULL);
372 packet_check_eom();
373 session_close(s);
374 return;
376 default:
378 * Any unknown messages in this phase are ignored,
379 * and a failure message is returned.
381 logit("Unknown packet type received after authentication: %d", type);
383 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
384 packet_send();
385 packet_write_wait();
387 /* Enable compression now that we have replied if appropriate. */
388 if (enable_compression_after_reply) {
389 enable_compression_after_reply = 0;
390 packet_start_compression(compression_level);
396 * This is called to fork and execute a command when we have no tty. This
397 * will call do_child from the child, and server_loop from the parent after
398 * setting up file descriptors and such.
400 void
401 do_exec_no_pty(Session *s, const char *command)
403 pid_t pid;
405 #ifdef USE_PIPES
406 int pin[2], pout[2], perr[2];
407 /* Allocate pipes for communicating with the program. */
408 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
409 packet_disconnect("Could not create pipes: %.100s",
410 strerror(errno));
411 #else /* USE_PIPES */
412 int inout[2], err[2];
413 /* Uses socket pairs to communicate with the program. */
414 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
415 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
416 packet_disconnect("Could not create socket pairs: %.100s",
417 strerror(errno));
418 #endif /* USE_PIPES */
419 if (s == NULL)
420 fatal("do_exec_no_pty: no session");
422 session_proctitle(s);
424 #if defined(USE_PAM)
425 if (options.use_pam && !use_privsep)
426 do_pam_setcred(1);
427 #endif /* USE_PAM */
429 /* Fork the child. */
430 if ((pid = fork()) == 0) {
431 is_child = 1;
433 /* Child. Reinitialize the log since the pid has changed. */
434 log_init(__progname, options.log_level, options.log_facility, log_stderr);
437 * Create a new session and process group since the 4.4BSD
438 * setlogin() affects the entire process group.
440 if (setsid() < 0)
441 error("setsid failed: %.100s", strerror(errno));
443 #ifdef USE_PIPES
445 * Redirect stdin. We close the parent side of the socket
446 * pair, and make the child side the standard input.
448 close(pin[1]);
449 if (dup2(pin[0], 0) < 0)
450 perror("dup2 stdin");
451 close(pin[0]);
453 /* Redirect stdout. */
454 close(pout[0]);
455 if (dup2(pout[1], 1) < 0)
456 perror("dup2 stdout");
457 close(pout[1]);
459 /* Redirect stderr. */
460 close(perr[0]);
461 if (dup2(perr[1], 2) < 0)
462 perror("dup2 stderr");
463 close(perr[1]);
464 #else /* USE_PIPES */
466 * Redirect stdin, stdout, and stderr. Stdin and stdout will
467 * use the same socket, as some programs (particularly rdist)
468 * seem to depend on it.
470 close(inout[1]);
471 close(err[1]);
472 if (dup2(inout[0], 0) < 0) /* stdin */
473 perror("dup2 stdin");
474 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
475 perror("dup2 stdout");
476 if (dup2(err[0], 2) < 0) /* stderr */
477 perror("dup2 stderr");
478 #endif /* USE_PIPES */
480 #ifdef _UNICOS
481 cray_init_job(s->pw); /* set up cray jid and tmpdir */
482 #endif
484 /* Do processing for the child (exec command etc). */
485 do_child(s, command);
486 /* NOTREACHED */
488 #ifdef _UNICOS
489 signal(WJSIGNAL, cray_job_termination_handler);
490 #endif /* _UNICOS */
491 #ifdef HAVE_CYGWIN
492 if (is_winnt)
493 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
494 #endif
495 if (pid < 0)
496 packet_disconnect("fork failed: %.100s", strerror(errno));
497 s->pid = pid;
498 /* Set interactive/non-interactive mode. */
499 packet_set_interactive(s->display != NULL);
500 #ifdef USE_PIPES
501 /* We are the parent. Close the child sides of the pipes. */
502 close(pin[0]);
503 close(pout[1]);
504 close(perr[1]);
506 if (compat20) {
507 if (s->is_subsystem) {
508 close(perr[0]);
509 perr[0] = -1;
511 session_set_fds(s, pin[1], pout[0], perr[0]);
512 } else {
513 /* Enter the interactive session. */
514 server_loop(pid, pin[1], pout[0], perr[0]);
515 /* server_loop has closed pin[1], pout[0], and perr[0]. */
517 #else /* USE_PIPES */
518 /* We are the parent. Close the child sides of the socket pairs. */
519 close(inout[0]);
520 close(err[0]);
523 * Clear loginmsg, since it's the child's responsibility to display
524 * it to the user, otherwise multiple sessions may accumulate
525 * multiple copies of the login messages.
527 buffer_clear(&loginmsg);
530 * Enter the interactive session. Note: server_loop must be able to
531 * handle the case that fdin and fdout are the same.
533 if (compat20) {
534 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
535 } else {
536 server_loop(pid, inout[1], inout[1], err[1]);
537 /* server_loop has closed inout[1] and err[1]. */
539 #endif /* USE_PIPES */
543 * This is called to fork and execute a command when we have a tty. This
544 * will call do_child from the child, and server_loop from the parent after
545 * setting up file descriptors, controlling tty, updating wtmp, utmp,
546 * lastlog, and other such operations.
548 void
549 do_exec_pty(Session *s, const char *command)
551 int fdout, ptyfd, ttyfd, ptymaster;
552 pid_t pid;
554 if (s == NULL)
555 fatal("do_exec_pty: no session");
556 ptyfd = s->ptyfd;
557 ttyfd = s->ttyfd;
559 #if defined(USE_PAM)
560 if (options.use_pam) {
561 do_pam_set_tty(s->tty);
562 if (!use_privsep)
563 do_pam_setcred(1);
565 #endif
567 /* Fork the child. */
568 if ((pid = fork()) == 0) {
569 is_child = 1;
571 /* Child. Reinitialize the log because the pid has changed. */
572 log_init(__progname, options.log_level, options.log_facility, log_stderr);
573 /* Close the master side of the pseudo tty. */
574 close(ptyfd);
576 /* Make the pseudo tty our controlling tty. */
577 pty_make_controlling_tty(&ttyfd, s->tty);
579 /* Redirect stdin/stdout/stderr from the pseudo tty. */
580 if (dup2(ttyfd, 0) < 0)
581 error("dup2 stdin: %s", strerror(errno));
582 if (dup2(ttyfd, 1) < 0)
583 error("dup2 stdout: %s", strerror(errno));
584 if (dup2(ttyfd, 2) < 0)
585 error("dup2 stderr: %s", strerror(errno));
587 /* Close the extra descriptor for the pseudo tty. */
588 close(ttyfd);
590 /* record login, etc. similar to login(1) */
591 #ifndef HAVE_OSF_SIA
592 if (!(options.use_login && command == NULL)) {
593 #ifdef _UNICOS
594 cray_init_job(s->pw); /* set up cray jid and tmpdir */
595 #endif /* _UNICOS */
596 do_login(s, command);
598 # ifdef LOGIN_NEEDS_UTMPX
599 else
600 do_pre_login(s);
601 # endif
602 #endif
604 /* Do common processing for the child, such as execing the command. */
605 do_child(s, command);
606 /* NOTREACHED */
608 #ifdef _UNICOS
609 signal(WJSIGNAL, cray_job_termination_handler);
610 #endif /* _UNICOS */
611 #ifdef HAVE_CYGWIN
612 if (is_winnt)
613 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
614 #endif
615 if (pid < 0)
616 packet_disconnect("fork failed: %.100s", strerror(errno));
617 s->pid = pid;
619 /* Parent. Close the slave side of the pseudo tty. */
620 close(ttyfd);
623 * Create another descriptor of the pty master side for use as the
624 * standard input. We could use the original descriptor, but this
625 * simplifies code in server_loop. The descriptor is bidirectional.
627 fdout = dup(ptyfd);
628 if (fdout < 0)
629 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
631 /* we keep a reference to the pty master */
632 ptymaster = dup(ptyfd);
633 if (ptymaster < 0)
634 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
635 s->ptymaster = ptymaster;
637 /* Enter interactive session. */
638 packet_set_interactive(1);
639 if (compat20) {
640 session_set_fds(s, ptyfd, fdout, -1);
641 } else {
642 server_loop(pid, ptyfd, fdout, -1);
643 /* server_loop _has_ closed ptyfd and fdout. */
647 #ifdef LOGIN_NEEDS_UTMPX
648 static void
649 do_pre_login(Session *s)
651 socklen_t fromlen;
652 struct sockaddr_storage from;
653 pid_t pid = getpid();
656 * Get IP address of client. If the connection is not a socket, let
657 * the address be 0.0.0.0.
659 memset(&from, 0, sizeof(from));
660 fromlen = sizeof(from);
661 if (packet_connection_is_on_socket()) {
662 if (getpeername(packet_get_connection_in(),
663 (struct sockaddr *)&from, &fromlen) < 0) {
664 debug("getpeername: %.100s", strerror(errno));
665 cleanup_exit(255);
669 record_utmp_only(pid, s->tty, s->pw->pw_name,
670 get_remote_name_or_ip(utmp_len, options.use_dns),
671 (struct sockaddr *)&from, fromlen);
673 #endif
676 * This is called to fork and execute a command. If another command is
677 * to be forced, execute that instead.
679 void
680 do_exec(Session *s, const char *command)
682 if (options.adm_forced_command) {
683 original_command = command;
684 command = options.adm_forced_command;
685 debug("Forced command (config) '%.900s'", command);
686 } else if (forced_command) {
687 original_command = command;
688 command = forced_command;
689 debug("Forced command (key option) '%.900s'", command);
692 #ifdef SSH_AUDIT_EVENTS
693 if (command != NULL)
694 PRIVSEP(audit_run_command(command));
695 else if (s->ttyfd == -1) {
696 char *shell = s->pw->pw_shell;
698 if (shell[0] == '\0') /* empty shell means /bin/sh */
699 shell =_PATH_BSHELL;
700 PRIVSEP(audit_run_command(shell));
702 #endif
704 if (s->ttyfd != -1)
705 do_exec_pty(s, command);
706 else
707 do_exec_no_pty(s, command);
709 original_command = NULL;
712 * Clear loginmsg: it's the child's responsibility to display
713 * it to the user, otherwise multiple sessions may accumulate
714 * multiple copies of the login messages.
716 buffer_clear(&loginmsg);
719 /* administrative, login(1)-like work */
720 void
721 do_login(Session *s, const char *command)
723 socklen_t fromlen;
724 struct sockaddr_storage from;
725 struct passwd * pw = s->pw;
726 pid_t pid = getpid();
729 * Get IP address of client. If the connection is not a socket, let
730 * the address be 0.0.0.0.
732 memset(&from, 0, sizeof(from));
733 fromlen = sizeof(from);
734 if (packet_connection_is_on_socket()) {
735 if (getpeername(packet_get_connection_in(),
736 (struct sockaddr *) & from, &fromlen) < 0) {
737 debug("getpeername: %.100s", strerror(errno));
738 cleanup_exit(255);
742 /* Record that there was a login on that tty from the remote host. */
743 if (!use_privsep)
744 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
745 get_remote_name_or_ip(utmp_len,
746 options.use_dns),
747 (struct sockaddr *)&from, fromlen);
749 #ifdef USE_PAM
751 * If password change is needed, do it now.
752 * This needs to occur before the ~/.hushlogin check.
754 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
755 display_loginmsg();
756 do_pam_chauthtok();
757 s->authctxt->force_pwchange = 0;
758 /* XXX - signal [net] parent to enable forwardings */
760 #endif
762 if (check_quietlogin(s, command))
763 return;
765 display_loginmsg();
767 do_motd();
771 * Display the message of the day.
773 void
774 do_motd(void)
776 FILE *f;
777 char buf[256];
779 if (options.print_motd) {
780 #ifdef HAVE_LOGIN_CAP
781 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
782 "/etc/motd"), "r");
783 #else
784 f = fopen("/etc/motd", "r");
785 #endif
786 if (f) {
787 while (fgets(buf, sizeof(buf), f))
788 fputs(buf, stdout);
789 fclose(f);
796 * Check for quiet login, either .hushlogin or command given.
799 check_quietlogin(Session *s, const char *command)
801 char buf[256];
802 struct passwd *pw = s->pw;
803 struct stat st;
805 /* Return 1 if .hushlogin exists or a command given. */
806 if (command != NULL)
807 return 1;
808 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
809 #ifdef HAVE_LOGIN_CAP
810 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
811 return 1;
812 #else
813 if (stat(buf, &st) >= 0)
814 return 1;
815 #endif
816 return 0;
820 * Sets the value of the given variable in the environment. If the variable
821 * already exists, its value is overriden.
823 void
824 child_set_env(char ***envp, u_int *envsizep, const char *name,
825 const char *value)
827 char **env;
828 u_int envsize;
829 u_int i, namelen;
832 * If we're passed an uninitialized list, allocate a single null
833 * entry before continuing.
835 if (*envp == NULL && *envsizep == 0) {
836 *envp = xmalloc(sizeof(char *));
837 *envp[0] = NULL;
838 *envsizep = 1;
842 * Find the slot where the value should be stored. If the variable
843 * already exists, we reuse the slot; otherwise we append a new slot
844 * at the end of the array, expanding if necessary.
846 env = *envp;
847 namelen = strlen(name);
848 for (i = 0; env[i]; i++)
849 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
850 break;
851 if (env[i]) {
852 /* Reuse the slot. */
853 xfree(env[i]);
854 } else {
855 /* New variable. Expand if necessary. */
856 envsize = *envsizep;
857 if (i >= envsize - 1) {
858 if (envsize >= 1000)
859 fatal("child_set_env: too many env vars");
860 envsize += 50;
861 env = (*envp) = xrealloc(env, envsize, sizeof(char *));
862 *envsizep = envsize;
864 /* Need to set the NULL pointer at end of array beyond the new slot. */
865 env[i + 1] = NULL;
868 /* Allocate space and format the variable in the appropriate slot. */
869 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
870 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
874 * Reads environment variables from the given file and adds/overrides them
875 * into the environment. If the file does not exist, this does nothing.
876 * Otherwise, it must consist of empty lines, comments (line starts with '#')
877 * and assignments of the form name=value. No other forms are allowed.
879 static void
880 read_environment_file(char ***env, u_int *envsize,
881 const char *filename)
883 FILE *f;
884 char buf[4096];
885 char *cp, *value;
886 u_int lineno = 0;
888 f = fopen(filename, "r");
889 if (!f)
890 return;
892 while (fgets(buf, sizeof(buf), f)) {
893 if (++lineno > 1000)
894 fatal("Too many lines in environment file %s", filename);
895 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
897 if (!*cp || *cp == '#' || *cp == '\n')
898 continue;
899 if (strchr(cp, '\n'))
900 *strchr(cp, '\n') = '\0';
901 value = strchr(cp, '=');
902 if (value == NULL) {
903 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
904 filename);
905 continue;
908 * Replace the equals sign by nul, and advance value to
909 * the value string.
911 *value = '\0';
912 value++;
913 child_set_env(env, envsize, cp, value);
915 fclose(f);
918 #ifdef HAVE_ETC_DEFAULT_LOGIN
920 * Return named variable from specified environment, or NULL if not present.
922 static char *
923 child_get_env(char **env, const char *name)
925 int i;
926 size_t len;
928 len = strlen(name);
929 for (i=0; env[i] != NULL; i++)
930 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
931 return(env[i] + len + 1);
932 return NULL;
936 * Read /etc/default/login.
937 * We pick up the PATH (or SUPATH for root) and UMASK.
939 static void
940 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
942 char **tmpenv = NULL, *var;
943 u_int i, tmpenvsize = 0;
944 u_long mask;
947 * We don't want to copy the whole file to the child's environment,
948 * so we use a temporary environment and copy the variables we're
949 * interested in.
951 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
953 if (tmpenv == NULL)
954 return;
956 if (uid == 0)
957 var = child_get_env(tmpenv, "SUPATH");
958 else
959 var = child_get_env(tmpenv, "PATH");
960 if (var != NULL)
961 child_set_env(env, envsize, "PATH", var);
963 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
964 if (sscanf(var, "%5lo", &mask) == 1)
965 umask((mode_t)mask);
967 for (i = 0; tmpenv[i] != NULL; i++)
968 xfree(tmpenv[i]);
969 xfree(tmpenv);
971 #endif /* HAVE_ETC_DEFAULT_LOGIN */
973 void
974 copy_environment(char **source, char ***env, u_int *envsize)
976 char *var_name, *var_val;
977 int i;
979 if (source == NULL)
980 return;
982 for(i = 0; source[i] != NULL; i++) {
983 var_name = xstrdup(source[i]);
984 if ((var_val = strstr(var_name, "=")) == NULL) {
985 xfree(var_name);
986 continue;
988 *var_val++ = '\0';
990 debug3("Copy environment: %s=%s", var_name, var_val);
991 child_set_env(env, envsize, var_name, var_val);
993 xfree(var_name);
997 static char **
998 do_setup_env(Session *s, const char *shell)
1000 char buf[256];
1001 u_int i, envsize;
1002 char **env, *laddr;
1003 struct passwd *pw = s->pw;
1004 #ifndef HAVE_LOGIN_CAP
1005 char *path = NULL;
1006 #endif
1008 /* Initialize the environment. */
1009 envsize = 100;
1010 env = xcalloc(envsize, sizeof(char *));
1011 env[0] = NULL;
1013 #ifdef HAVE_CYGWIN
1015 * The Windows environment contains some setting which are
1016 * important for a running system. They must not be dropped.
1019 char **p;
1021 p = fetch_windows_environment();
1022 copy_environment(p, &env, &envsize);
1023 free_windows_environment(p);
1025 #endif
1027 #ifdef GSSAPI
1028 /* Allow any GSSAPI methods that we've used to alter
1029 * the childs environment as they see fit
1031 ssh_gssapi_do_child(&env, &envsize);
1032 #endif
1034 if (!options.use_login) {
1035 /* Set basic environment. */
1036 for (i = 0; i < s->num_env; i++)
1037 child_set_env(&env, &envsize, s->env[i].name,
1038 s->env[i].val);
1040 child_set_env(&env, &envsize, "USER", pw->pw_name);
1041 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1042 #ifdef _AIX
1043 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1044 #endif
1045 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1046 #ifdef HAVE_LOGIN_CAP
1047 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1048 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1049 else
1050 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1051 #else /* HAVE_LOGIN_CAP */
1052 # ifndef HAVE_CYGWIN
1054 * There's no standard path on Windows. The path contains
1055 * important components pointing to the system directories,
1056 * needed for loading shared libraries. So the path better
1057 * remains intact here.
1059 # ifdef HAVE_ETC_DEFAULT_LOGIN
1060 read_etc_default_login(&env, &envsize, pw->pw_uid);
1061 path = child_get_env(env, "PATH");
1062 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1063 if (path == NULL || *path == '\0') {
1064 child_set_env(&env, &envsize, "PATH",
1065 s->pw->pw_uid == 0 ?
1066 SUPERUSER_PATH : _PATH_STDPATH);
1068 # endif /* HAVE_CYGWIN */
1069 #endif /* HAVE_LOGIN_CAP */
1071 snprintf(buf, sizeof buf, "%.200s/%.50s",
1072 _PATH_MAILDIR, pw->pw_name);
1073 child_set_env(&env, &envsize, "MAIL", buf);
1075 /* Normal systems set SHELL by default. */
1076 child_set_env(&env, &envsize, "SHELL", shell);
1078 if (getenv("TZ"))
1079 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1081 /* Set custom environment options from RSA authentication. */
1082 if (!options.use_login) {
1083 while (custom_environment) {
1084 struct envstring *ce = custom_environment;
1085 char *str = ce->s;
1087 for (i = 0; str[i] != '=' && str[i]; i++)
1089 if (str[i] == '=') {
1090 str[i] = 0;
1091 child_set_env(&env, &envsize, str, str + i + 1);
1093 custom_environment = ce->next;
1094 xfree(ce->s);
1095 xfree(ce);
1099 /* SSH_CLIENT deprecated */
1100 snprintf(buf, sizeof buf, "%.50s %d %d",
1101 get_remote_ipaddr(), get_remote_port(), get_local_port());
1102 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1104 laddr = get_local_ipaddr(packet_get_connection_in());
1105 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1106 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1107 xfree(laddr);
1108 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1110 if (s->ttyfd != -1)
1111 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1112 if (s->term)
1113 child_set_env(&env, &envsize, "TERM", s->term);
1114 if (s->display)
1115 child_set_env(&env, &envsize, "DISPLAY", s->display);
1116 if (original_command)
1117 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1118 original_command);
1120 #ifdef _UNICOS
1121 if (cray_tmpdir[0] != '\0')
1122 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1123 #endif /* _UNICOS */
1126 * Since we clear KRB5CCNAME at startup, if it's set now then it
1127 * must have been set by a native authentication method (eg AIX or
1128 * SIA), so copy it to the child.
1131 char *cp;
1133 if ((cp = getenv("KRB5CCNAME")) != NULL)
1134 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1137 #ifdef _AIX
1139 char *cp;
1141 if ((cp = getenv("AUTHSTATE")) != NULL)
1142 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1143 read_environment_file(&env, &envsize, "/etc/environment");
1145 #endif
1146 #ifdef KRB5
1147 if (s->authctxt->krb5_ccname)
1148 child_set_env(&env, &envsize, "KRB5CCNAME",
1149 s->authctxt->krb5_ccname);
1150 #endif
1151 #ifdef USE_PAM
1153 * Pull in any environment variables that may have
1154 * been set by PAM.
1156 if (options.use_pam) {
1157 char **p;
1159 p = fetch_pam_child_environment();
1160 copy_environment(p, &env, &envsize);
1161 free_pam_environment(p);
1163 p = fetch_pam_environment();
1164 copy_environment(p, &env, &envsize);
1165 free_pam_environment(p);
1167 #endif /* USE_PAM */
1169 if (auth_sock_name != NULL)
1170 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1171 auth_sock_name);
1173 /* read $HOME/.ssh/environment. */
1174 if (options.permit_user_env && !options.use_login) {
1175 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1176 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1177 read_environment_file(&env, &envsize, buf);
1179 if (debug_flag) {
1180 /* dump the environment */
1181 fprintf(stderr, "Environment:\n");
1182 for (i = 0; env[i]; i++)
1183 fprintf(stderr, " %.200s\n", env[i]);
1185 return env;
1189 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1190 * first in this order).
1192 static void
1193 do_rc_files(Session *s, const char *shell)
1195 FILE *f = NULL;
1196 char cmd[1024];
1197 int do_xauth;
1198 struct stat st;
1200 do_xauth =
1201 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1203 /* ignore _PATH_SSH_USER_RC for subsystems */
1204 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1205 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1206 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1207 if (debug_flag)
1208 fprintf(stderr, "Running %s\n", cmd);
1209 f = popen(cmd, "w");
1210 if (f) {
1211 if (do_xauth)
1212 fprintf(f, "%s %s\n", s->auth_proto,
1213 s->auth_data);
1214 pclose(f);
1215 } else
1216 fprintf(stderr, "Could not run %s\n",
1217 _PATH_SSH_USER_RC);
1218 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1219 if (debug_flag)
1220 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1221 _PATH_SSH_SYSTEM_RC);
1222 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1223 if (f) {
1224 if (do_xauth)
1225 fprintf(f, "%s %s\n", s->auth_proto,
1226 s->auth_data);
1227 pclose(f);
1228 } else
1229 fprintf(stderr, "Could not run %s\n",
1230 _PATH_SSH_SYSTEM_RC);
1231 } else if (do_xauth && options.xauth_location != NULL) {
1232 /* Add authority data to .Xauthority if appropriate. */
1233 if (debug_flag) {
1234 fprintf(stderr,
1235 "Running %.500s remove %.100s\n",
1236 options.xauth_location, s->auth_display);
1237 fprintf(stderr,
1238 "%.500s add %.100s %.100s %.100s\n",
1239 options.xauth_location, s->auth_display,
1240 s->auth_proto, s->auth_data);
1242 snprintf(cmd, sizeof cmd, "%s -q -",
1243 options.xauth_location);
1244 f = popen(cmd, "w");
1245 if (f) {
1246 fprintf(f, "remove %s\n",
1247 s->auth_display);
1248 fprintf(f, "add %s %s %s\n",
1249 s->auth_display, s->auth_proto,
1250 s->auth_data);
1251 pclose(f);
1252 } else {
1253 fprintf(stderr, "Could not run %s\n",
1254 cmd);
1259 static void
1260 do_nologin(struct passwd *pw)
1262 FILE *f = NULL;
1263 char buf[1024];
1265 #ifdef HAVE_LOGIN_CAP
1266 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1267 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1268 _PATH_NOLOGIN), "r");
1269 #else
1270 if (pw->pw_uid)
1271 f = fopen(_PATH_NOLOGIN, "r");
1272 #endif
1273 if (f) {
1274 /* /etc/nologin exists. Print its contents and exit. */
1275 logit("User %.100s not allowed because %s exists",
1276 pw->pw_name, _PATH_NOLOGIN);
1277 while (fgets(buf, sizeof(buf), f))
1278 fputs(buf, stderr);
1279 fclose(f);
1280 fflush(NULL);
1281 exit(254);
1285 /* Set login name, uid, gid, and groups. */
1286 void
1287 do_setusercontext(struct passwd *pw)
1289 #ifndef HAVE_CYGWIN
1290 if (getuid() == 0 || geteuid() == 0)
1291 #endif /* HAVE_CYGWIN */
1294 #ifdef HAVE_SETPCRED
1295 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1296 fatal("Failed to set process credentials");
1297 #endif /* HAVE_SETPCRED */
1298 #ifdef HAVE_LOGIN_CAP
1299 # ifdef __bsdi__
1300 setpgid(0, 0);
1301 # endif
1302 #ifdef GSSAPI
1303 if (options.gss_authentication) {
1304 temporarily_use_uid(pw);
1305 ssh_gssapi_storecreds();
1306 restore_uid();
1308 #endif
1309 # ifdef USE_PAM
1310 if (options.use_pam) {
1311 do_pam_session();
1312 do_pam_setcred(0);
1314 # endif /* USE_PAM */
1315 if (setusercontext(lc, pw, pw->pw_uid,
1316 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1317 perror("unable to set user context");
1318 exit(1);
1320 #else
1321 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1322 /* Sets login uid for accounting */
1323 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1324 error("setluid: %s", strerror(errno));
1325 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1327 if (setlogin(pw->pw_name) < 0)
1328 error("setlogin failed: %s", strerror(errno));
1329 if (setgid(pw->pw_gid) < 0) {
1330 perror("setgid");
1331 exit(1);
1333 /* Initialize the group list. */
1334 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1335 perror("initgroups");
1336 exit(1);
1338 endgrent();
1339 #ifdef GSSAPI
1340 if (options.gss_authentication) {
1341 temporarily_use_uid(pw);
1342 ssh_gssapi_storecreds();
1343 restore_uid();
1345 #endif
1346 # ifdef USE_PAM
1348 * PAM credentials may take the form of supplementary groups.
1349 * These will have been wiped by the above initgroups() call.
1350 * Reestablish them here.
1352 if (options.use_pam) {
1353 do_pam_session();
1354 do_pam_setcred(0);
1356 # endif /* USE_PAM */
1357 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1358 irix_setusercontext(pw);
1359 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1360 # ifdef _AIX
1361 aix_usrinfo(pw);
1362 # endif /* _AIX */
1363 #if defined(HAVE_LIBIAF) && !defined(BROKEN_LIBIAF)
1364 if (set_id(pw->pw_name) != 0) {
1365 exit(1);
1367 #endif /* HAVE_LIBIAF && !BROKEN_LIBIAF */
1368 /* Permanently switch to the desired uid. */
1369 permanently_set_uid(pw);
1370 #endif
1373 #ifdef HAVE_CYGWIN
1374 if (is_winnt)
1375 #endif
1376 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1377 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1379 #ifdef WITH_SELINUX
1380 ssh_selinux_setup_exec_context(pw->pw_name);
1381 #endif
1384 static void
1385 do_pwchange(Session *s)
1387 fflush(NULL);
1388 fprintf(stderr, "WARNING: Your password has expired.\n");
1389 if (s->ttyfd != -1) {
1390 fprintf(stderr,
1391 "You must change your password now and login again!\n");
1392 #ifdef PASSWD_NEEDS_USERNAME
1393 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1394 (char *)NULL);
1395 #else
1396 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1397 #endif
1398 perror("passwd");
1399 } else {
1400 fprintf(stderr,
1401 "Password change required but no TTY available.\n");
1403 exit(1);
1406 static void
1407 launch_login(struct passwd *pw, const char *hostname)
1409 /* Launch login(1). */
1411 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1412 #ifdef xxxLOGIN_NEEDS_TERM
1413 (s->term ? s->term : "unknown"),
1414 #endif /* LOGIN_NEEDS_TERM */
1415 #ifdef LOGIN_NO_ENDOPT
1416 "-p", "-f", pw->pw_name, (char *)NULL);
1417 #else
1418 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1419 #endif
1421 /* Login couldn't be executed, die. */
1423 perror("login");
1424 exit(1);
1427 static void
1428 child_close_fds(void)
1430 int i;
1432 if (packet_get_connection_in() == packet_get_connection_out())
1433 close(packet_get_connection_in());
1434 else {
1435 close(packet_get_connection_in());
1436 close(packet_get_connection_out());
1439 * Close all descriptors related to channels. They will still remain
1440 * open in the parent.
1442 /* XXX better use close-on-exec? -markus */
1443 channel_close_all();
1446 * Close any extra file descriptors. Note that there may still be
1447 * descriptors left by system functions. They will be closed later.
1449 endpwent();
1452 * Close any extra open file descriptors so that we don't have them
1453 * hanging around in clients. Note that we want to do this after
1454 * initgroups, because at least on Solaris 2.3 it leaves file
1455 * descriptors open.
1457 for (i = 3; i < 64; i++)
1458 close(i);
1462 * Performs common processing for the child, such as setting up the
1463 * environment, closing extra file descriptors, setting the user and group
1464 * ids, and executing the command or shell.
1466 void
1467 do_child(Session *s, const char *command)
1469 extern char **environ;
1470 char **env;
1471 char *argv[10];
1472 const char *shell, *shell0, *hostname = NULL;
1473 struct passwd *pw = s->pw;
1475 /* remove hostkey from the child's memory */
1476 destroy_sensitive_data();
1478 /* Force a password change */
1479 if (s->authctxt->force_pwchange) {
1480 do_setusercontext(pw);
1481 child_close_fds();
1482 do_pwchange(s);
1483 exit(1);
1486 /* login(1) is only called if we execute the login shell */
1487 if (options.use_login && command != NULL)
1488 options.use_login = 0;
1490 #ifdef _UNICOS
1491 cray_setup(pw->pw_uid, pw->pw_name, command);
1492 #endif /* _UNICOS */
1495 * Login(1) does this as well, and it needs uid 0 for the "-h"
1496 * switch, so we let login(1) to this for us.
1498 if (!options.use_login) {
1499 #ifdef HAVE_OSF_SIA
1500 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1501 if (!check_quietlogin(s, command))
1502 do_motd();
1503 #else /* HAVE_OSF_SIA */
1504 /* When PAM is enabled we rely on it to do the nologin check */
1505 if (!options.use_pam)
1506 do_nologin(pw);
1507 do_setusercontext(pw);
1509 * PAM session modules in do_setusercontext may have
1510 * generated messages, so if this in an interactive
1511 * login then display them too.
1513 if (!check_quietlogin(s, command))
1514 display_loginmsg();
1515 #endif /* HAVE_OSF_SIA */
1518 #ifdef USE_PAM
1519 if (options.use_pam && !options.use_login && !is_pam_session_open()) {
1520 debug3("PAM session not opened, exiting");
1521 display_loginmsg();
1522 exit(254);
1524 #endif
1527 * Get the shell from the password data. An empty shell field is
1528 * legal, and means /bin/sh.
1530 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1533 * Make sure $SHELL points to the shell from the password file,
1534 * even if shell is overridden from login.conf
1536 env = do_setup_env(s, shell);
1538 #ifdef HAVE_LOGIN_CAP
1539 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1540 #endif
1542 /* we have to stash the hostname before we close our socket. */
1543 if (options.use_login)
1544 hostname = get_remote_name_or_ip(utmp_len,
1545 options.use_dns);
1547 * Close the connection descriptors; note that this is the child, and
1548 * the server will still have the socket open, and it is important
1549 * that we do not shutdown it. Note that the descriptors cannot be
1550 * closed before building the environment, as we call
1551 * get_remote_ipaddr there.
1553 child_close_fds();
1556 * Must take new environment into use so that .ssh/rc,
1557 * /etc/ssh/sshrc and xauth are run in the proper environment.
1559 environ = env;
1561 #if defined(KRB5) && defined(USE_AFS)
1563 * At this point, we check to see if AFS is active and if we have
1564 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1565 * if we can (and need to) extend the ticket into an AFS token. If
1566 * we don't do this, we run into potential problems if the user's
1567 * home directory is in AFS and it's not world-readable.
1570 if (options.kerberos_get_afs_token && k_hasafs() &&
1571 (s->authctxt->krb5_ctx != NULL)) {
1572 char cell[64];
1574 debug("Getting AFS token");
1576 k_setpag();
1578 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1579 krb5_afslog(s->authctxt->krb5_ctx,
1580 s->authctxt->krb5_fwd_ccache, cell, NULL);
1582 krb5_afslog_home(s->authctxt->krb5_ctx,
1583 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1585 #endif
1587 /* Change current directory to the user's home directory. */
1588 if (chdir(pw->pw_dir) < 0) {
1589 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1590 pw->pw_dir, strerror(errno));
1591 #ifdef HAVE_LOGIN_CAP
1592 if (login_getcapbool(lc, "requirehome", 0))
1593 exit(1);
1594 #endif
1597 if (!options.use_login)
1598 do_rc_files(s, shell);
1600 /* restore SIGPIPE for child */
1601 signal(SIGPIPE, SIG_DFL);
1603 if (options.use_login) {
1604 launch_login(pw, hostname);
1605 /* NEVERREACHED */
1608 /* Get the last component of the shell name. */
1609 if ((shell0 = strrchr(shell, '/')) != NULL)
1610 shell0++;
1611 else
1612 shell0 = shell;
1615 * If we have no command, execute the shell. In this case, the shell
1616 * name to be passed in argv[0] is preceded by '-' to indicate that
1617 * this is a login shell.
1619 if (!command) {
1620 char argv0[256];
1622 /* Start the shell. Set initial character to '-'. */
1623 argv0[0] = '-';
1625 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1626 >= sizeof(argv0) - 1) {
1627 errno = EINVAL;
1628 perror(shell);
1629 exit(1);
1632 /* Execute the shell. */
1633 argv[0] = argv0;
1634 argv[1] = NULL;
1635 execve(shell, argv, env);
1637 /* Executing the shell failed. */
1638 perror(shell);
1639 exit(1);
1642 * Execute the command using the user's shell. This uses the -c
1643 * option to execute the command.
1645 argv[0] = (char *) shell0;
1646 argv[1] = "-c";
1647 argv[2] = (char *) command;
1648 argv[3] = NULL;
1649 execve(shell, argv, env);
1650 perror(shell);
1651 exit(1);
1654 Session *
1655 session_new(void)
1657 int i;
1658 static int did_init = 0;
1659 if (!did_init) {
1660 debug("session_new: init");
1661 for (i = 0; i < MAX_SESSIONS; i++) {
1662 sessions[i].used = 0;
1664 did_init = 1;
1666 for (i = 0; i < MAX_SESSIONS; i++) {
1667 Session *s = &sessions[i];
1668 if (! s->used) {
1669 memset(s, 0, sizeof(*s));
1670 s->chanid = -1;
1671 s->ptyfd = -1;
1672 s->ttyfd = -1;
1673 s->used = 1;
1674 s->self = i;
1675 s->x11_chanids = NULL;
1676 debug("session_new: session %d", i);
1677 return s;
1680 return NULL;
1683 static void
1684 session_dump(void)
1686 int i;
1687 for (i = 0; i < MAX_SESSIONS; i++) {
1688 Session *s = &sessions[i];
1689 debug("dump: used %d session %d %p channel %d pid %ld",
1690 s->used,
1691 s->self,
1693 s->chanid,
1694 (long)s->pid);
1699 session_open(Authctxt *authctxt, int chanid)
1701 Session *s = session_new();
1702 debug("session_open: channel %d", chanid);
1703 if (s == NULL) {
1704 error("no more sessions");
1705 return 0;
1707 s->authctxt = authctxt;
1708 s->pw = authctxt->pw;
1709 if (s->pw == NULL || !authctxt->valid)
1710 fatal("no user for session %d", s->self);
1711 debug("session_open: session %d: link with channel %d", s->self, chanid);
1712 s->chanid = chanid;
1713 return 1;
1716 Session *
1717 session_by_tty(char *tty)
1719 int i;
1720 for (i = 0; i < MAX_SESSIONS; i++) {
1721 Session *s = &sessions[i];
1722 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1723 debug("session_by_tty: session %d tty %s", i, tty);
1724 return s;
1727 debug("session_by_tty: unknown tty %.100s", tty);
1728 session_dump();
1729 return NULL;
1732 static Session *
1733 session_by_channel(int id)
1735 int i;
1736 for (i = 0; i < MAX_SESSIONS; i++) {
1737 Session *s = &sessions[i];
1738 if (s->used && s->chanid == id) {
1739 debug("session_by_channel: session %d channel %d", i, id);
1740 return s;
1743 debug("session_by_channel: unknown channel %d", id);
1744 session_dump();
1745 return NULL;
1748 static Session *
1749 session_by_x11_channel(int id)
1751 int i, j;
1753 for (i = 0; i < MAX_SESSIONS; i++) {
1754 Session *s = &sessions[i];
1756 if (s->x11_chanids == NULL || !s->used)
1757 continue;
1758 for (j = 0; s->x11_chanids[j] != -1; j++) {
1759 if (s->x11_chanids[j] == id) {
1760 debug("session_by_x11_channel: session %d "
1761 "channel %d", s->self, id);
1762 return s;
1766 debug("session_by_x11_channel: unknown channel %d", id);
1767 session_dump();
1768 return NULL;
1771 static Session *
1772 session_by_pid(pid_t pid)
1774 int i;
1775 debug("session_by_pid: pid %ld", (long)pid);
1776 for (i = 0; i < MAX_SESSIONS; i++) {
1777 Session *s = &sessions[i];
1778 if (s->used && s->pid == pid)
1779 return s;
1781 error("session_by_pid: unknown pid %ld", (long)pid);
1782 session_dump();
1783 return NULL;
1786 static int
1787 session_window_change_req(Session *s)
1789 s->col = packet_get_int();
1790 s->row = packet_get_int();
1791 s->xpixel = packet_get_int();
1792 s->ypixel = packet_get_int();
1793 packet_check_eom();
1794 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1795 return 1;
1798 static int
1799 session_pty_req(Session *s)
1801 u_int len;
1802 int n_bytes;
1804 if (no_pty_flag) {
1805 debug("Allocating a pty not permitted for this authentication.");
1806 return 0;
1808 if (s->ttyfd != -1) {
1809 packet_disconnect("Protocol error: you already have a pty.");
1810 return 0;
1813 s->term = packet_get_string(&len);
1815 if (compat20) {
1816 s->col = packet_get_int();
1817 s->row = packet_get_int();
1818 } else {
1819 s->row = packet_get_int();
1820 s->col = packet_get_int();
1822 s->xpixel = packet_get_int();
1823 s->ypixel = packet_get_int();
1825 if (strcmp(s->term, "") == 0) {
1826 xfree(s->term);
1827 s->term = NULL;
1830 /* Allocate a pty and open it. */
1831 debug("Allocating pty.");
1832 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1833 if (s->term)
1834 xfree(s->term);
1835 s->term = NULL;
1836 s->ptyfd = -1;
1837 s->ttyfd = -1;
1838 error("session_pty_req: session %d alloc failed", s->self);
1839 return 0;
1841 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1843 /* for SSH1 the tty modes length is not given */
1844 if (!compat20)
1845 n_bytes = packet_remaining();
1846 tty_parse_modes(s->ttyfd, &n_bytes);
1848 if (!use_privsep)
1849 pty_setowner(s->pw, s->tty);
1851 /* Set window size from the packet. */
1852 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1854 packet_check_eom();
1855 session_proctitle(s);
1856 return 1;
1859 static int
1860 session_subsystem_req(Session *s)
1862 struct stat st;
1863 u_int len;
1864 int success = 0;
1865 char *prog, *cmd, *subsys = packet_get_string(&len);
1866 u_int i;
1868 packet_check_eom();
1869 logit("subsystem request for %.100s", subsys);
1871 for (i = 0; i < options.num_subsystems; i++) {
1872 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1873 prog = options.subsystem_command[i];
1874 cmd = options.subsystem_args[i];
1875 if (stat(prog, &st) < 0) {
1876 error("subsystem: cannot stat %s: %s", prog,
1877 strerror(errno));
1878 break;
1880 debug("subsystem: exec() %s", cmd);
1881 s->is_subsystem = 1;
1882 do_exec(s, cmd);
1883 success = 1;
1884 break;
1888 if (!success)
1889 logit("subsystem request for %.100s failed, subsystem not found",
1890 subsys);
1892 xfree(subsys);
1893 return success;
1896 static int
1897 session_x11_req(Session *s)
1899 int success;
1901 if (s->auth_proto != NULL || s->auth_data != NULL) {
1902 error("session_x11_req: session %d: "
1903 "x11 forwarding already active", s->self);
1904 return 0;
1906 s->single_connection = packet_get_char();
1907 s->auth_proto = packet_get_string(NULL);
1908 s->auth_data = packet_get_string(NULL);
1909 s->screen = packet_get_int();
1910 packet_check_eom();
1912 success = session_setup_x11fwd(s);
1913 if (!success) {
1914 xfree(s->auth_proto);
1915 xfree(s->auth_data);
1916 s->auth_proto = NULL;
1917 s->auth_data = NULL;
1919 return success;
1922 static int
1923 session_shell_req(Session *s)
1925 packet_check_eom();
1926 do_exec(s, NULL);
1927 return 1;
1930 static int
1931 session_exec_req(Session *s)
1933 u_int len;
1934 char *command = packet_get_string(&len);
1935 packet_check_eom();
1936 do_exec(s, command);
1937 xfree(command);
1938 return 1;
1941 static int
1942 session_break_req(Session *s)
1945 packet_get_int(); /* ignored */
1946 packet_check_eom();
1948 if (s->ttyfd == -1 ||
1949 tcsendbreak(s->ttyfd, 0) < 0)
1950 return 0;
1951 return 1;
1954 static int
1955 session_env_req(Session *s)
1957 char *name, *val;
1958 u_int name_len, val_len, i;
1960 name = packet_get_string(&name_len);
1961 val = packet_get_string(&val_len);
1962 packet_check_eom();
1964 /* Don't set too many environment variables */
1965 if (s->num_env > 128) {
1966 debug2("Ignoring env request %s: too many env vars", name);
1967 goto fail;
1970 for (i = 0; i < options.num_accept_env; i++) {
1971 if (match_pattern(name, options.accept_env[i])) {
1972 debug2("Setting env %d: %s=%s", s->num_env, name, val);
1973 s->env = xrealloc(s->env, s->num_env + 1,
1974 sizeof(*s->env));
1975 s->env[s->num_env].name = name;
1976 s->env[s->num_env].val = val;
1977 s->num_env++;
1978 return (1);
1981 debug2("Ignoring env request %s: disallowed name", name);
1983 fail:
1984 xfree(name);
1985 xfree(val);
1986 return (0);
1989 static int
1990 session_auth_agent_req(Session *s)
1992 static int called = 0;
1993 packet_check_eom();
1994 if (no_agent_forwarding_flag) {
1995 debug("session_auth_agent_req: no_agent_forwarding_flag");
1996 return 0;
1998 if (called) {
1999 return 0;
2000 } else {
2001 called = 1;
2002 return auth_input_request_forwarding(s->pw);
2007 session_input_channel_req(Channel *c, const char *rtype)
2009 int success = 0;
2010 Session *s;
2012 if ((s = session_by_channel(c->self)) == NULL) {
2013 logit("session_input_channel_req: no session %d req %.100s",
2014 c->self, rtype);
2015 return 0;
2017 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2020 * a session is in LARVAL state until a shell, a command
2021 * or a subsystem is executed
2023 if (c->type == SSH_CHANNEL_LARVAL) {
2024 if (strcmp(rtype, "shell") == 0) {
2025 success = session_shell_req(s);
2026 } else if (strcmp(rtype, "exec") == 0) {
2027 success = session_exec_req(s);
2028 } else if (strcmp(rtype, "pty-req") == 0) {
2029 success = session_pty_req(s);
2030 } else if (strcmp(rtype, "x11-req") == 0) {
2031 success = session_x11_req(s);
2032 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2033 success = session_auth_agent_req(s);
2034 } else if (strcmp(rtype, "subsystem") == 0) {
2035 success = session_subsystem_req(s);
2036 } else if (strcmp(rtype, "env") == 0) {
2037 success = session_env_req(s);
2040 if (strcmp(rtype, "window-change") == 0) {
2041 success = session_window_change_req(s);
2042 } else if (strcmp(rtype, "break") == 0) {
2043 success = session_break_req(s);
2046 return success;
2049 void
2050 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2052 if (!compat20)
2053 fatal("session_set_fds: called for proto != 2.0");
2055 * now that have a child and a pipe to the child,
2056 * we can activate our channel and register the fd's
2058 if (s->chanid == -1)
2059 fatal("no channel for session %d", s->self);
2060 channel_set_fds(s->chanid,
2061 fdout, fdin, fderr,
2062 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2064 CHAN_SES_WINDOW_DEFAULT);
2068 * Function to perform pty cleanup. Also called if we get aborted abnormally
2069 * (e.g., due to a dropped connection).
2071 void
2072 session_pty_cleanup2(Session *s)
2074 if (s == NULL) {
2075 error("session_pty_cleanup: no session");
2076 return;
2078 if (s->ttyfd == -1)
2079 return;
2081 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2083 /* Record that the user has logged out. */
2084 if (s->pid != 0)
2085 record_logout(s->pid, s->tty, s->pw->pw_name);
2087 /* Release the pseudo-tty. */
2088 if (getuid() == 0)
2089 pty_release(s->tty);
2092 * Close the server side of the socket pairs. We must do this after
2093 * the pty cleanup, so that another process doesn't get this pty
2094 * while we're still cleaning up.
2096 if (close(s->ptymaster) < 0)
2097 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2099 /* unlink pty from session */
2100 s->ttyfd = -1;
2103 void
2104 session_pty_cleanup(Session *s)
2106 PRIVSEP(session_pty_cleanup2(s));
2109 static char *
2110 sig2name(int sig)
2112 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2113 SSH_SIG(ABRT);
2114 SSH_SIG(ALRM);
2115 SSH_SIG(FPE);
2116 SSH_SIG(HUP);
2117 SSH_SIG(ILL);
2118 SSH_SIG(INT);
2119 SSH_SIG(KILL);
2120 SSH_SIG(PIPE);
2121 SSH_SIG(QUIT);
2122 SSH_SIG(SEGV);
2123 SSH_SIG(TERM);
2124 SSH_SIG(USR1);
2125 SSH_SIG(USR2);
2126 #undef SSH_SIG
2127 return "SIG@openssh.com";
2130 static void
2131 session_close_x11(int id)
2133 Channel *c;
2135 if ((c = channel_by_id(id)) == NULL) {
2136 debug("session_close_x11: x11 channel %d missing", id);
2137 } else {
2138 /* Detach X11 listener */
2139 debug("session_close_x11: detach x11 channel %d", id);
2140 channel_cancel_cleanup(id);
2141 if (c->ostate != CHAN_OUTPUT_CLOSED)
2142 chan_mark_dead(c);
2146 static void
2147 session_close_single_x11(int id, void *arg)
2149 Session *s;
2150 u_int i;
2152 debug3("session_close_single_x11: channel %d", id);
2153 channel_cancel_cleanup(id);
2154 if ((s = session_by_x11_channel(id)) == NULL)
2155 fatal("session_close_single_x11: no x11 channel %d", id);
2156 for (i = 0; s->x11_chanids[i] != -1; i++) {
2157 debug("session_close_single_x11: session %d: "
2158 "closing channel %d", s->self, s->x11_chanids[i]);
2160 * The channel "id" is already closing, but make sure we
2161 * close all of its siblings.
2163 if (s->x11_chanids[i] != id)
2164 session_close_x11(s->x11_chanids[i]);
2166 xfree(s->x11_chanids);
2167 s->x11_chanids = NULL;
2168 if (s->display) {
2169 xfree(s->display);
2170 s->display = NULL;
2172 if (s->auth_proto) {
2173 xfree(s->auth_proto);
2174 s->auth_proto = NULL;
2176 if (s->auth_data) {
2177 xfree(s->auth_data);
2178 s->auth_data = NULL;
2180 if (s->auth_display) {
2181 xfree(s->auth_display);
2182 s->auth_display = NULL;
2186 static void
2187 session_exit_message(Session *s, int status)
2189 Channel *c;
2191 if ((c = channel_lookup(s->chanid)) == NULL)
2192 fatal("session_exit_message: session %d: no channel %d",
2193 s->self, s->chanid);
2194 debug("session_exit_message: session %d channel %d pid %ld",
2195 s->self, s->chanid, (long)s->pid);
2197 if (WIFEXITED(status)) {
2198 channel_request_start(s->chanid, "exit-status", 0);
2199 packet_put_int(WEXITSTATUS(status));
2200 packet_send();
2201 } else if (WIFSIGNALED(status)) {
2202 channel_request_start(s->chanid, "exit-signal", 0);
2203 packet_put_cstring(sig2name(WTERMSIG(status)));
2204 #ifdef WCOREDUMP
2205 packet_put_char(WCOREDUMP(status));
2206 #else /* WCOREDUMP */
2207 packet_put_char(0);
2208 #endif /* WCOREDUMP */
2209 packet_put_cstring("");
2210 packet_put_cstring("");
2211 packet_send();
2212 } else {
2213 /* Some weird exit cause. Just exit. */
2214 packet_disconnect("wait returned status %04x.", status);
2217 /* disconnect channel */
2218 debug("session_exit_message: release channel %d", s->chanid);
2221 * Adjust cleanup callback attachment to send close messages when
2222 * the channel gets EOF. The session will be then be closed
2223 * by session_close_by_channel when the childs close their fds.
2225 channel_register_cleanup(c->self, session_close_by_channel, 1);
2228 * emulate a write failure with 'chan_write_failed', nobody will be
2229 * interested in data we write.
2230 * Note that we must not call 'chan_read_failed', since there could
2231 * be some more data waiting in the pipe.
2233 if (c->ostate != CHAN_OUTPUT_CLOSED)
2234 chan_write_failed(c);
2237 void
2238 session_close(Session *s)
2240 u_int i;
2242 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2243 if (s->ttyfd != -1)
2244 session_pty_cleanup(s);
2245 if (s->term)
2246 xfree(s->term);
2247 if (s->display)
2248 xfree(s->display);
2249 if (s->x11_chanids)
2250 xfree(s->x11_chanids);
2251 if (s->auth_display)
2252 xfree(s->auth_display);
2253 if (s->auth_data)
2254 xfree(s->auth_data);
2255 if (s->auth_proto)
2256 xfree(s->auth_proto);
2257 s->used = 0;
2258 for (i = 0; i < s->num_env; i++) {
2259 xfree(s->env[i].name);
2260 xfree(s->env[i].val);
2262 if (s->env != NULL)
2263 xfree(s->env);
2264 session_proctitle(s);
2267 void
2268 session_close_by_pid(pid_t pid, int status)
2270 Session *s = session_by_pid(pid);
2271 if (s == NULL) {
2272 debug("session_close_by_pid: no session for pid %ld",
2273 (long)pid);
2274 return;
2276 if (s->chanid != -1)
2277 session_exit_message(s, status);
2278 if (s->ttyfd != -1)
2279 session_pty_cleanup(s);
2280 s->pid = 0;
2284 * this is called when a channel dies before
2285 * the session 'child' itself dies
2287 void
2288 session_close_by_channel(int id, void *arg)
2290 Session *s = session_by_channel(id);
2291 u_int i;
2293 if (s == NULL) {
2294 debug("session_close_by_channel: no session for id %d", id);
2295 return;
2297 debug("session_close_by_channel: channel %d child %ld",
2298 id, (long)s->pid);
2299 if (s->pid != 0) {
2300 debug("session_close_by_channel: channel %d: has child", id);
2302 * delay detach of session, but release pty, since
2303 * the fd's to the child are already closed
2305 if (s->ttyfd != -1)
2306 session_pty_cleanup(s);
2307 return;
2309 /* detach by removing callback */
2310 channel_cancel_cleanup(s->chanid);
2312 /* Close any X11 listeners associated with this session */
2313 if (s->x11_chanids != NULL) {
2314 for (i = 0; s->x11_chanids[i] != -1; i++) {
2315 session_close_x11(s->x11_chanids[i]);
2316 s->x11_chanids[i] = -1;
2320 s->chanid = -1;
2321 session_close(s);
2324 void
2325 session_destroy_all(void (*closefunc)(Session *))
2327 int i;
2328 for (i = 0; i < MAX_SESSIONS; i++) {
2329 Session *s = &sessions[i];
2330 if (s->used) {
2331 if (closefunc != NULL)
2332 closefunc(s);
2333 else
2334 session_close(s);
2339 static char *
2340 session_tty_list(void)
2342 static char buf[1024];
2343 int i;
2344 char *cp;
2346 buf[0] = '\0';
2347 for (i = 0; i < MAX_SESSIONS; i++) {
2348 Session *s = &sessions[i];
2349 if (s->used && s->ttyfd != -1) {
2351 if (strncmp(s->tty, "/dev/", 5) != 0) {
2352 cp = strrchr(s->tty, '/');
2353 cp = (cp == NULL) ? s->tty : cp + 1;
2354 } else
2355 cp = s->tty + 5;
2357 if (buf[0] != '\0')
2358 strlcat(buf, ",", sizeof buf);
2359 strlcat(buf, cp, sizeof buf);
2362 if (buf[0] == '\0')
2363 strlcpy(buf, "notty", sizeof buf);
2364 return buf;
2367 void
2368 session_proctitle(Session *s)
2370 if (s->pw == NULL)
2371 error("no user for session %d", s->self);
2372 else
2373 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2377 session_setup_x11fwd(Session *s)
2379 struct stat st;
2380 char display[512], auth_display[512];
2381 char hostname[MAXHOSTNAMELEN];
2382 u_int i;
2384 if (no_x11_forwarding_flag) {
2385 packet_send_debug("X11 forwarding disabled in user configuration file.");
2386 return 0;
2388 if (!options.x11_forwarding) {
2389 debug("X11 forwarding disabled in server configuration file.");
2390 return 0;
2392 if (!options.xauth_location ||
2393 (stat(options.xauth_location, &st) == -1)) {
2394 packet_send_debug("No xauth program; cannot forward with spoofing.");
2395 return 0;
2397 if (options.use_login) {
2398 packet_send_debug("X11 forwarding disabled; "
2399 "not compatible with UseLogin=yes.");
2400 return 0;
2402 if (s->display != NULL) {
2403 debug("X11 display already set.");
2404 return 0;
2406 if (x11_create_display_inet(options.x11_display_offset,
2407 options.x11_use_localhost, s->single_connection,
2408 &s->display_number, &s->x11_chanids) == -1) {
2409 debug("x11_create_display_inet failed.");
2410 return 0;
2412 for (i = 0; s->x11_chanids[i] != -1; i++) {
2413 channel_register_cleanup(s->x11_chanids[i],
2414 session_close_single_x11, 0);
2417 /* Set up a suitable value for the DISPLAY variable. */
2418 if (gethostname(hostname, sizeof(hostname)) < 0)
2419 fatal("gethostname: %.100s", strerror(errno));
2421 * auth_display must be used as the displayname when the
2422 * authorization entry is added with xauth(1). This will be
2423 * different than the DISPLAY string for localhost displays.
2425 if (options.x11_use_localhost) {
2426 snprintf(display, sizeof display, "localhost:%u.%u",
2427 s->display_number, s->screen);
2428 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2429 s->display_number, s->screen);
2430 s->display = xstrdup(display);
2431 s->auth_display = xstrdup(auth_display);
2432 } else {
2433 #ifdef IPADDR_IN_DISPLAY
2434 struct hostent *he;
2435 struct in_addr my_addr;
2437 he = gethostbyname(hostname);
2438 if (he == NULL) {
2439 error("Can't get IP address for X11 DISPLAY.");
2440 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2441 return 0;
2443 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2444 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2445 s->display_number, s->screen);
2446 #else
2447 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2448 s->display_number, s->screen);
2449 #endif
2450 s->display = xstrdup(display);
2451 s->auth_display = xstrdup(display);
2454 return 1;
2457 static void
2458 do_authenticated2(Authctxt *authctxt)
2460 server_loop2(authctxt);
2463 void
2464 do_cleanup(Authctxt *authctxt)
2466 static int called = 0;
2468 debug("do_cleanup");
2470 /* no cleanup if we're in the child for login shell */
2471 if (is_child)
2472 return;
2474 /* avoid double cleanup */
2475 if (called)
2476 return;
2477 called = 1;
2479 if (authctxt == NULL || !authctxt->authenticated)
2480 return;
2481 #ifdef KRB5
2482 if (options.kerberos_ticket_cleanup &&
2483 authctxt->krb5_ctx)
2484 krb5_cleanup_proc(authctxt);
2485 #endif
2487 #ifdef GSSAPI
2488 if (compat20 && options.gss_cleanup_creds)
2489 ssh_gssapi_cleanup_creds();
2490 #endif
2492 #ifdef USE_PAM
2493 if (options.use_pam) {
2494 sshpam_cleanup();
2495 sshpam_thread_cleanup();
2497 #endif
2499 /* remove agent socket */
2500 auth_sock_cleanup_proc(authctxt->pw);
2503 * Cleanup ptys/utmp only if privsep is disabled,
2504 * or if running in monitor.
2506 if (!use_privsep || mm_is_monitor())
2507 session_destroy_all(session_pty_cleanup2);