1 /* $OpenBSD: session.c,v 1.204 2006/07/02 22:45:59 stevesk Exp $ */
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
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
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.
38 #include <sys/types.h>
39 #ifdef HAVE_SYS_STAT_H
40 # include <sys/stat.h>
64 #include "auth-options.h"
65 #include "pathnames.h"
69 #include "serverloop.h"
73 #include "monitor_wrap.h"
75 #if defined(KRB5) && defined(USE_AFS)
85 Session *session_new(void);
86 void session_set_fds(Session *, int, int, int);
87 void session_pty_cleanup(Session *);
88 void session_proctitle(Session *);
89 int session_setup_x11fwd(Session *);
90 void do_exec_pty(Session *, const char *);
91 void do_exec_no_pty(Session *, const char *);
92 void do_exec(Session *, const char *);
93 void do_login(Session *, const char *);
94 #ifdef LOGIN_NEEDS_UTMPX
95 static void do_pre_login(Session *s);
97 void do_child(Session *, const char *);
99 int check_quietlogin(Session *, const char *);
101 static void do_authenticated1(Authctxt *);
102 static void do_authenticated2(Authctxt *);
104 static int session_pty_req(Session *);
107 extern ServerOptions options;
108 extern char *__progname;
109 extern int log_stderr;
110 extern int debug_flag;
111 extern u_int utmp_len;
112 extern int startup_pipe;
113 extern void destroy_sensitive_data(void);
114 extern Buffer loginmsg;
116 /* original command from peer. */
117 const char *original_command = NULL;
120 #define MAX_SESSIONS 10
121 Session sessions[MAX_SESSIONS];
123 #ifdef HAVE_LOGIN_CAP
127 static int is_child = 0;
129 /* Name and directory of socket for authentication agent forwarding. */
130 static char *auth_sock_name = NULL;
131 static char *auth_sock_dir = NULL;
133 /* removes the agent forwarding socket */
136 auth_sock_cleanup_proc(struct passwd *pw)
138 if (auth_sock_name != NULL) {
139 temporarily_use_uid(pw);
140 unlink(auth_sock_name);
141 rmdir(auth_sock_dir);
142 auth_sock_name = NULL;
148 auth_input_request_forwarding(struct passwd * pw)
152 struct sockaddr_un sunaddr;
154 if (auth_sock_name != NULL) {
155 error("authentication forwarding requested twice.");
159 /* Temporarily drop privileged uid for mkdir/bind. */
160 temporarily_use_uid(pw);
162 /* Allocate a buffer for the socket name, and format the name. */
163 auth_sock_name = xmalloc(MAXPATHLEN);
164 auth_sock_dir = xmalloc(MAXPATHLEN);
165 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
167 /* Create private directory for socket */
168 if (mkdtemp(auth_sock_dir) == NULL) {
169 packet_send_debug("Agent forwarding disabled: "
170 "mkdtemp() failed: %.100s", strerror(errno));
172 xfree(auth_sock_name);
173 xfree(auth_sock_dir);
174 auth_sock_name = NULL;
175 auth_sock_dir = NULL;
178 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
179 auth_sock_dir, (long) getpid());
181 /* Create the socket. */
182 sock = socket(AF_UNIX, SOCK_STREAM, 0);
184 packet_disconnect("socket: %.100s", strerror(errno));
186 /* Bind it to the name. */
187 memset(&sunaddr, 0, sizeof(sunaddr));
188 sunaddr.sun_family = AF_UNIX;
189 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
191 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0)
192 packet_disconnect("bind: %.100s", strerror(errno));
194 /* Restore the privileged uid. */
197 /* Start listening on the socket. */
198 if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
199 packet_disconnect("listen: %.100s", strerror(errno));
201 /* Allocate a channel for the authentication agent socket. */
202 nc = channel_new("auth socket",
203 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
204 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
205 0, "auth socket", 1);
206 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
211 display_loginmsg(void)
213 if (buffer_len(&loginmsg) > 0) {
214 buffer_append(&loginmsg, "\0", 1);
215 printf("%s", (char *)buffer_ptr(&loginmsg));
216 buffer_clear(&loginmsg);
221 do_authenticated(Authctxt *authctxt)
223 setproctitle("%s", authctxt->pw->pw_name);
225 /* setup the channel layer */
226 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
227 channel_permit_all_opens();
230 do_authenticated2(authctxt);
232 do_authenticated1(authctxt);
234 do_cleanup(authctxt);
238 * Prepares for an interactive session. This is called after the user has
239 * been successfully authenticated. During this message exchange, pseudo
240 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
241 * are requested, etc.
244 do_authenticated1(Authctxt *authctxt)
248 int success, type, screen_flag;
249 int enable_compression_after_reply = 0;
250 u_int proto_len, data_len, dlen, compression_level = 0;
254 error("no more sessions");
257 s->authctxt = authctxt;
258 s->pw = authctxt->pw;
261 * We stay in this loop until the client requests to execute a shell
267 /* Get a packet from the client. */
268 type = packet_read();
270 /* Process the packet. */
272 case SSH_CMSG_REQUEST_COMPRESSION:
273 compression_level = packet_get_int();
275 if (compression_level < 1 || compression_level > 9) {
276 packet_send_debug("Received invalid compression level %d.",
280 if (options.compression == COMP_NONE) {
281 debug2("compression disabled");
284 /* Enable compression after we have responded with SUCCESS. */
285 enable_compression_after_reply = 1;
289 case SSH_CMSG_REQUEST_PTY:
290 success = session_pty_req(s);
293 case SSH_CMSG_X11_REQUEST_FORWARDING:
294 s->auth_proto = packet_get_string(&proto_len);
295 s->auth_data = packet_get_string(&data_len);
297 screen_flag = packet_get_protocol_flags() &
298 SSH_PROTOFLAG_SCREEN_NUMBER;
299 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
301 if (packet_remaining() == 4) {
303 debug2("Buggy client: "
304 "X11 screen flag missing");
305 s->screen = packet_get_int();
310 success = session_setup_x11fwd(s);
312 xfree(s->auth_proto);
314 s->auth_proto = NULL;
319 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
320 if (no_agent_forwarding_flag || compat13) {
321 debug("Authentication agent forwarding not permitted for this authentication.");
324 debug("Received authentication agent forwarding request.");
325 success = auth_input_request_forwarding(s->pw);
328 case SSH_CMSG_PORT_FORWARD_REQUEST:
329 if (no_port_forwarding_flag) {
330 debug("Port forwarding not permitted for this authentication.");
333 if (!options.allow_tcp_forwarding) {
334 debug("Port forwarding not permitted.");
337 debug("Received TCP/IP port forwarding request.");
338 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
342 case SSH_CMSG_MAX_PACKET_SIZE:
343 if (packet_set_maxsize(packet_get_int()) > 0)
347 case SSH_CMSG_EXEC_SHELL:
348 case SSH_CMSG_EXEC_CMD:
349 if (type == SSH_CMSG_EXEC_CMD) {
350 command = packet_get_string(&dlen);
351 debug("Exec command '%.500s'", command);
363 * Any unknown messages in this phase are ignored,
364 * and a failure message is returned.
366 logit("Unknown packet type received after authentication: %d", type);
368 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
372 /* Enable compression now that we have replied if appropriate. */
373 if (enable_compression_after_reply) {
374 enable_compression_after_reply = 0;
375 packet_start_compression(compression_level);
381 * This is called to fork and execute a command when we have no tty. This
382 * will call do_child from the child, and server_loop from the parent after
383 * setting up file descriptors and such.
386 do_exec_no_pty(Session *s, const char *command)
391 int pin[2], pout[2], perr[2];
392 /* Allocate pipes for communicating with the program. */
393 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
394 packet_disconnect("Could not create pipes: %.100s",
396 #else /* USE_PIPES */
397 int inout[2], err[2];
398 /* Uses socket pairs to communicate with the program. */
399 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
400 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
401 packet_disconnect("Could not create socket pairs: %.100s",
403 #endif /* USE_PIPES */
405 fatal("do_exec_no_pty: no session");
407 session_proctitle(s);
410 if (options.use_pam && !use_privsep)
414 /* Fork the child. */
415 if ((pid = fork()) == 0) {
418 /* Child. Reinitialize the log since the pid has changed. */
419 log_init(__progname, options.log_level, options.log_facility, log_stderr);
422 * Create a new session and process group since the 4.4BSD
423 * setlogin() affects the entire process group.
426 error("setsid failed: %.100s", strerror(errno));
430 * Redirect stdin. We close the parent side of the socket
431 * pair, and make the child side the standard input.
434 if (dup2(pin[0], 0) < 0)
435 perror("dup2 stdin");
438 /* Redirect stdout. */
440 if (dup2(pout[1], 1) < 0)
441 perror("dup2 stdout");
444 /* Redirect stderr. */
446 if (dup2(perr[1], 2) < 0)
447 perror("dup2 stderr");
449 #else /* USE_PIPES */
451 * Redirect stdin, stdout, and stderr. Stdin and stdout will
452 * use the same socket, as some programs (particularly rdist)
453 * seem to depend on it.
457 if (dup2(inout[0], 0) < 0) /* stdin */
458 perror("dup2 stdin");
459 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
460 perror("dup2 stdout");
461 if (dup2(err[0], 2) < 0) /* stderr */
462 perror("dup2 stderr");
463 #endif /* USE_PIPES */
466 cray_init_job(s->pw); /* set up cray jid and tmpdir */
469 /* Do processing for the child (exec command etc). */
470 do_child(s, command);
474 signal(WJSIGNAL, cray_job_termination_handler);
478 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
481 packet_disconnect("fork failed: %.100s", strerror(errno));
483 /* Set interactive/non-interactive mode. */
484 packet_set_interactive(s->display != NULL);
486 /* We are the parent. Close the child sides of the pipes. */
492 if (s->is_subsystem) {
496 session_set_fds(s, pin[1], pout[0], perr[0]);
498 /* Enter the interactive session. */
499 server_loop(pid, pin[1], pout[0], perr[0]);
500 /* server_loop has closed pin[1], pout[0], and perr[0]. */
502 #else /* USE_PIPES */
503 /* We are the parent. Close the child sides of the socket pairs. */
508 * Clear loginmsg, since it's the child's responsibility to display
509 * it to the user, otherwise multiple sessions may accumulate
510 * multiple copies of the login messages.
512 buffer_clear(&loginmsg);
515 * Enter the interactive session. Note: server_loop must be able to
516 * handle the case that fdin and fdout are the same.
519 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
521 server_loop(pid, inout[1], inout[1], err[1]);
522 /* server_loop has closed inout[1] and err[1]. */
524 #endif /* USE_PIPES */
528 * This is called to fork and execute a command when we have a tty. This
529 * will call do_child from the child, and server_loop from the parent after
530 * setting up file descriptors, controlling tty, updating wtmp, utmp,
531 * lastlog, and other such operations.
534 do_exec_pty(Session *s, const char *command)
536 int fdout, ptyfd, ttyfd, ptymaster;
540 fatal("do_exec_pty: no session");
545 if (options.use_pam) {
546 do_pam_set_tty(s->tty);
552 /* Fork the child. */
553 if ((pid = fork()) == 0) {
556 /* Child. Reinitialize the log because the pid has changed. */
557 log_init(__progname, options.log_level, options.log_facility, log_stderr);
558 /* Close the master side of the pseudo tty. */
561 /* Make the pseudo tty our controlling tty. */
562 pty_make_controlling_tty(&ttyfd, s->tty);
564 /* Redirect stdin/stdout/stderr from the pseudo tty. */
565 if (dup2(ttyfd, 0) < 0)
566 error("dup2 stdin: %s", strerror(errno));
567 if (dup2(ttyfd, 1) < 0)
568 error("dup2 stdout: %s", strerror(errno));
569 if (dup2(ttyfd, 2) < 0)
570 error("dup2 stderr: %s", strerror(errno));
572 /* Close the extra descriptor for the pseudo tty. */
575 /* record login, etc. similar to login(1) */
577 if (!(options.use_login && command == NULL)) {
579 cray_init_job(s->pw); /* set up cray jid and tmpdir */
581 do_login(s, command);
583 # ifdef LOGIN_NEEDS_UTMPX
589 /* Do common processing for the child, such as execing the command. */
590 do_child(s, command);
594 signal(WJSIGNAL, cray_job_termination_handler);
598 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
601 packet_disconnect("fork failed: %.100s", strerror(errno));
604 /* Parent. Close the slave side of the pseudo tty. */
608 * Create another descriptor of the pty master side for use as the
609 * standard input. We could use the original descriptor, but this
610 * simplifies code in server_loop. The descriptor is bidirectional.
614 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
616 /* we keep a reference to the pty master */
617 ptymaster = dup(ptyfd);
619 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
620 s->ptymaster = ptymaster;
622 /* Enter interactive session. */
623 packet_set_interactive(1);
625 session_set_fds(s, ptyfd, fdout, -1);
627 server_loop(pid, ptyfd, fdout, -1);
628 /* server_loop _has_ closed ptyfd and fdout. */
632 #ifdef LOGIN_NEEDS_UTMPX
634 do_pre_login(Session *s)
637 struct sockaddr_storage from;
638 pid_t pid = getpid();
641 * Get IP address of client. If the connection is not a socket, let
642 * the address be 0.0.0.0.
644 memset(&from, 0, sizeof(from));
645 fromlen = sizeof(from);
646 if (packet_connection_is_on_socket()) {
647 if (getpeername(packet_get_connection_in(),
648 (struct sockaddr *)&from, &fromlen) < 0) {
649 debug("getpeername: %.100s", strerror(errno));
654 record_utmp_only(pid, s->tty, s->pw->pw_name,
655 get_remote_name_or_ip(utmp_len, options.use_dns),
656 (struct sockaddr *)&from, fromlen);
661 * This is called to fork and execute a command. If another command is
662 * to be forced, execute that instead.
665 do_exec(Session *s, const char *command)
667 if (forced_command) {
668 original_command = command;
669 command = forced_command;
670 debug("Forced command '%.900s'", command);
673 #ifdef SSH_AUDIT_EVENTS
675 PRIVSEP(audit_run_command(command));
676 else if (s->ttyfd == -1) {
677 char *shell = s->pw->pw_shell;
679 if (shell[0] == '\0') /* empty shell means /bin/sh */
681 PRIVSEP(audit_run_command(shell));
686 do_exec_pty(s, command);
688 do_exec_no_pty(s, command);
690 original_command = NULL;
693 * Clear loginmsg: it's the child's responsibility to display
694 * it to the user, otherwise multiple sessions may accumulate
695 * multiple copies of the login messages.
697 buffer_clear(&loginmsg);
700 /* administrative, login(1)-like work */
702 do_login(Session *s, const char *command)
705 struct sockaddr_storage from;
706 struct passwd * pw = s->pw;
707 pid_t pid = getpid();
710 * Get IP address of client. If the connection is not a socket, let
711 * the address be 0.0.0.0.
713 memset(&from, 0, sizeof(from));
714 fromlen = sizeof(from);
715 if (packet_connection_is_on_socket()) {
716 if (getpeername(packet_get_connection_in(),
717 (struct sockaddr *) & from, &fromlen) < 0) {
718 debug("getpeername: %.100s", strerror(errno));
723 /* Record that there was a login on that tty from the remote host. */
725 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
726 get_remote_name_or_ip(utmp_len,
728 (struct sockaddr *)&from, fromlen);
732 * If password change is needed, do it now.
733 * This needs to occur before the ~/.hushlogin check.
735 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
738 s->authctxt->force_pwchange = 0;
739 /* XXX - signal [net] parent to enable forwardings */
743 if (check_quietlogin(s, command))
752 * Display the message of the day.
760 if (options.print_motd) {
761 #ifdef HAVE_LOGIN_CAP
762 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
765 f = fopen("/etc/motd", "r");
768 while (fgets(buf, sizeof(buf), f))
777 * Check for quiet login, either .hushlogin or command given.
780 check_quietlogin(Session *s, const char *command)
783 struct passwd *pw = s->pw;
786 /* Return 1 if .hushlogin exists or a command given. */
789 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
790 #ifdef HAVE_LOGIN_CAP
791 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
794 if (stat(buf, &st) >= 0)
801 * Sets the value of the given variable in the environment. If the variable
802 * already exists, its value is overriden.
805 child_set_env(char ***envp, u_int *envsizep, const char *name,
813 * If we're passed an uninitialized list, allocate a single null
814 * entry before continuing.
816 if (*envp == NULL && *envsizep == 0) {
817 *envp = xmalloc(sizeof(char *));
823 * Find the slot where the value should be stored. If the variable
824 * already exists, we reuse the slot; otherwise we append a new slot
825 * at the end of the array, expanding if necessary.
828 namelen = strlen(name);
829 for (i = 0; env[i]; i++)
830 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
833 /* Reuse the slot. */
836 /* New variable. Expand if necessary. */
838 if (i >= envsize - 1) {
840 fatal("child_set_env: too many env vars");
842 env = (*envp) = xrealloc(env, envsize, sizeof(char *));
845 /* Need to set the NULL pointer at end of array beyond the new slot. */
849 /* Allocate space and format the variable in the appropriate slot. */
850 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
851 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
855 * Reads environment variables from the given file and adds/overrides them
856 * into the environment. If the file does not exist, this does nothing.
857 * Otherwise, it must consist of empty lines, comments (line starts with '#')
858 * and assignments of the form name=value. No other forms are allowed.
861 read_environment_file(char ***env, u_int *envsize,
862 const char *filename)
869 f = fopen(filename, "r");
873 while (fgets(buf, sizeof(buf), f)) {
875 fatal("Too many lines in environment file %s", filename);
876 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
878 if (!*cp || *cp == '#' || *cp == '\n')
880 if (strchr(cp, '\n'))
881 *strchr(cp, '\n') = '\0';
882 value = strchr(cp, '=');
884 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
889 * Replace the equals sign by nul, and advance value to
894 child_set_env(env, envsize, cp, value);
899 #ifdef HAVE_ETC_DEFAULT_LOGIN
901 * Return named variable from specified environment, or NULL if not present.
904 child_get_env(char **env, const char *name)
910 for (i=0; env[i] != NULL; i++)
911 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
912 return(env[i] + len + 1);
917 * Read /etc/default/login.
918 * We pick up the PATH (or SUPATH for root) and UMASK.
921 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
923 char **tmpenv = NULL, *var;
924 u_int i, tmpenvsize = 0;
928 * We don't want to copy the whole file to the child's environment,
929 * so we use a temporary environment and copy the variables we're
932 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
938 var = child_get_env(tmpenv, "SUPATH");
940 var = child_get_env(tmpenv, "PATH");
942 child_set_env(env, envsize, "PATH", var);
944 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
945 if (sscanf(var, "%5lo", &mask) == 1)
948 for (i = 0; tmpenv[i] != NULL; i++)
952 #endif /* HAVE_ETC_DEFAULT_LOGIN */
955 copy_environment(char **source, char ***env, u_int *envsize)
957 char *var_name, *var_val;
963 for(i = 0; source[i] != NULL; i++) {
964 var_name = xstrdup(source[i]);
965 if ((var_val = strstr(var_name, "=")) == NULL) {
971 debug3("Copy environment: %s=%s", var_name, var_val);
972 child_set_env(env, envsize, var_name, var_val);
979 do_setup_env(Session *s, const char *shell)
983 char **env, *laddr, *path = NULL;
984 struct passwd *pw = s->pw;
986 /* Initialize the environment. */
988 env = xcalloc(envsize, sizeof(char *));
993 * The Windows environment contains some setting which are
994 * important for a running system. They must not be dropped.
999 p = fetch_windows_environment();
1000 copy_environment(p, &env, &envsize);
1001 free_windows_environment(p);
1006 /* Allow any GSSAPI methods that we've used to alter
1007 * the childs environment as they see fit
1009 ssh_gssapi_do_child(&env, &envsize);
1012 if (!options.use_login) {
1013 /* Set basic environment. */
1014 for (i = 0; i < s->num_env; i++)
1015 child_set_env(&env, &envsize, s->env[i].name,
1018 child_set_env(&env, &envsize, "USER", pw->pw_name);
1019 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1021 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1023 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1024 #ifdef HAVE_LOGIN_CAP
1025 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1026 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1028 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1029 #else /* HAVE_LOGIN_CAP */
1030 # ifndef HAVE_CYGWIN
1032 * There's no standard path on Windows. The path contains
1033 * important components pointing to the system directories,
1034 * needed for loading shared libraries. So the path better
1035 * remains intact here.
1037 # ifdef HAVE_ETC_DEFAULT_LOGIN
1038 read_etc_default_login(&env, &envsize, pw->pw_uid);
1039 path = child_get_env(env, "PATH");
1040 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1041 if (path == NULL || *path == '\0') {
1042 child_set_env(&env, &envsize, "PATH",
1043 s->pw->pw_uid == 0 ?
1044 SUPERUSER_PATH : _PATH_STDPATH);
1046 # endif /* HAVE_CYGWIN */
1047 #endif /* HAVE_LOGIN_CAP */
1049 snprintf(buf, sizeof buf, "%.200s/%.50s",
1050 _PATH_MAILDIR, pw->pw_name);
1051 child_set_env(&env, &envsize, "MAIL", buf);
1053 /* Normal systems set SHELL by default. */
1054 child_set_env(&env, &envsize, "SHELL", shell);
1057 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1059 /* Set custom environment options from RSA authentication. */
1060 if (!options.use_login) {
1061 while (custom_environment) {
1062 struct envstring *ce = custom_environment;
1065 for (i = 0; str[i] != '=' && str[i]; i++)
1067 if (str[i] == '=') {
1069 child_set_env(&env, &envsize, str, str + i + 1);
1071 custom_environment = ce->next;
1077 /* SSH_CLIENT deprecated */
1078 snprintf(buf, sizeof buf, "%.50s %d %d",
1079 get_remote_ipaddr(), get_remote_port(), get_local_port());
1080 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1082 laddr = get_local_ipaddr(packet_get_connection_in());
1083 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1084 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1086 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1089 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1091 child_set_env(&env, &envsize, "TERM", s->term);
1093 child_set_env(&env, &envsize, "DISPLAY", s->display);
1094 if (original_command)
1095 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1099 if (cray_tmpdir[0] != '\0')
1100 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1101 #endif /* _UNICOS */
1104 * Since we clear KRB5CCNAME at startup, if it's set now then it
1105 * must have been set by a native authentication method (eg AIX or
1106 * SIA), so copy it to the child.
1111 if ((cp = getenv("KRB5CCNAME")) != NULL)
1112 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1119 if ((cp = getenv("AUTHSTATE")) != NULL)
1120 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1121 read_environment_file(&env, &envsize, "/etc/environment");
1125 if (s->authctxt->krb5_ccname)
1126 child_set_env(&env, &envsize, "KRB5CCNAME",
1127 s->authctxt->krb5_ccname);
1131 * Pull in any environment variables that may have
1134 if (options.use_pam) {
1137 p = fetch_pam_child_environment();
1138 copy_environment(p, &env, &envsize);
1139 free_pam_environment(p);
1141 p = fetch_pam_environment();
1142 copy_environment(p, &env, &envsize);
1143 free_pam_environment(p);
1145 #endif /* USE_PAM */
1147 if (auth_sock_name != NULL)
1148 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1151 /* read $HOME/.ssh/environment. */
1152 if (options.permit_user_env && !options.use_login) {
1153 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1154 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1155 read_environment_file(&env, &envsize, buf);
1158 /* dump the environment */
1159 fprintf(stderr, "Environment:\n");
1160 for (i = 0; env[i]; i++)
1161 fprintf(stderr, " %.200s\n", env[i]);
1167 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1168 * first in this order).
1171 do_rc_files(Session *s, const char *shell)
1179 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1181 /* ignore _PATH_SSH_USER_RC for subsystems */
1182 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1183 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1184 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1186 fprintf(stderr, "Running %s\n", cmd);
1187 f = popen(cmd, "w");
1190 fprintf(f, "%s %s\n", s->auth_proto,
1194 fprintf(stderr, "Could not run %s\n",
1196 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1198 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1199 _PATH_SSH_SYSTEM_RC);
1200 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1203 fprintf(f, "%s %s\n", s->auth_proto,
1207 fprintf(stderr, "Could not run %s\n",
1208 _PATH_SSH_SYSTEM_RC);
1209 } else if (do_xauth && options.xauth_location != NULL) {
1210 /* Add authority data to .Xauthority if appropriate. */
1213 "Running %.500s remove %.100s\n",
1214 options.xauth_location, s->auth_display);
1216 "%.500s add %.100s %.100s %.100s\n",
1217 options.xauth_location, s->auth_display,
1218 s->auth_proto, s->auth_data);
1220 snprintf(cmd, sizeof cmd, "%s -q -",
1221 options.xauth_location);
1222 f = popen(cmd, "w");
1224 fprintf(f, "remove %s\n",
1226 fprintf(f, "add %s %s %s\n",
1227 s->auth_display, s->auth_proto,
1231 fprintf(stderr, "Could not run %s\n",
1238 do_nologin(struct passwd *pw)
1243 #ifdef HAVE_LOGIN_CAP
1244 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1245 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1246 _PATH_NOLOGIN), "r");
1249 f = fopen(_PATH_NOLOGIN, "r");
1252 /* /etc/nologin exists. Print its contents and exit. */
1253 logit("User %.100s not allowed because %s exists",
1254 pw->pw_name, _PATH_NOLOGIN);
1255 while (fgets(buf, sizeof(buf), f))
1263 /* Set login name, uid, gid, and groups. */
1265 do_setusercontext(struct passwd *pw)
1268 if (getuid() == 0 || geteuid() == 0)
1269 #endif /* HAVE_CYGWIN */
1272 #ifdef HAVE_SETPCRED
1273 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1274 fatal("Failed to set process credentials");
1275 #endif /* HAVE_SETPCRED */
1276 #ifdef HAVE_LOGIN_CAP
1281 if (options.gss_authentication) {
1282 temporarily_use_uid(pw);
1283 ssh_gssapi_storecreds();
1288 if (options.use_pam) {
1292 # endif /* USE_PAM */
1293 if (setusercontext(lc, pw, pw->pw_uid,
1294 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1295 perror("unable to set user context");
1299 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1300 /* Sets login uid for accounting */
1301 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1302 error("setluid: %s", strerror(errno));
1303 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1305 if (setlogin(pw->pw_name) < 0)
1306 error("setlogin failed: %s", strerror(errno));
1307 if (setgid(pw->pw_gid) < 0) {
1311 /* Initialize the group list. */
1312 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1313 perror("initgroups");
1318 if (options.gss_authentication) {
1319 temporarily_use_uid(pw);
1320 ssh_gssapi_storecreds();
1326 * PAM credentials may take the form of supplementary groups.
1327 * These will have been wiped by the above initgroups() call.
1328 * Reestablish them here.
1330 if (options.use_pam) {
1334 # endif /* USE_PAM */
1335 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1336 irix_setusercontext(pw);
1337 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1341 #if defined(HAVE_LIBIAF) && !defined(BROKEN_LIBIAF)
1342 if (set_id(pw->pw_name) != 0) {
1345 #endif /* HAVE_LIBIAF && !BROKEN_LIBIAF */
1346 /* Permanently switch to the desired uid. */
1347 permanently_set_uid(pw);
1354 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1355 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1358 ssh_selinux_setup_exec_context(pw->pw_name);
1363 do_pwchange(Session *s)
1366 fprintf(stderr, "WARNING: Your password has expired.\n");
1367 if (s->ttyfd != -1) {
1369 "You must change your password now and login again!\n");
1370 #ifdef PASSWD_NEEDS_USERNAME
1371 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1374 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1379 "Password change required but no TTY available.\n");
1385 launch_login(struct passwd *pw, const char *hostname)
1387 /* Launch login(1). */
1389 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1390 #ifdef xxxLOGIN_NEEDS_TERM
1391 (s->term ? s->term : "unknown"),
1392 #endif /* LOGIN_NEEDS_TERM */
1393 #ifdef LOGIN_NO_ENDOPT
1394 "-p", "-f", pw->pw_name, (char *)NULL);
1396 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1399 /* Login couldn't be executed, die. */
1406 child_close_fds(void)
1410 if (packet_get_connection_in() == packet_get_connection_out())
1411 close(packet_get_connection_in());
1413 close(packet_get_connection_in());
1414 close(packet_get_connection_out());
1417 * Close all descriptors related to channels. They will still remain
1418 * open in the parent.
1420 /* XXX better use close-on-exec? -markus */
1421 channel_close_all();
1424 * Close any extra file descriptors. Note that there may still be
1425 * descriptors left by system functions. They will be closed later.
1430 * Close any extra open file descriptors so that we don't have them
1431 * hanging around in clients. Note that we want to do this after
1432 * initgroups, because at least on Solaris 2.3 it leaves file
1435 for (i = 3; i < 64; i++)
1440 * Performs common processing for the child, such as setting up the
1441 * environment, closing extra file descriptors, setting the user and group
1442 * ids, and executing the command or shell.
1445 do_child(Session *s, const char *command)
1447 extern char **environ;
1450 const char *shell, *shell0, *hostname = NULL;
1451 struct passwd *pw = s->pw;
1453 /* remove hostkey from the child's memory */
1454 destroy_sensitive_data();
1456 /* Force a password change */
1457 if (s->authctxt->force_pwchange) {
1458 do_setusercontext(pw);
1464 /* login(1) is only called if we execute the login shell */
1465 if (options.use_login && command != NULL)
1466 options.use_login = 0;
1469 cray_setup(pw->pw_uid, pw->pw_name, command);
1470 #endif /* _UNICOS */
1473 * Login(1) does this as well, and it needs uid 0 for the "-h"
1474 * switch, so we let login(1) to this for us.
1476 if (!options.use_login) {
1478 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1479 if (!check_quietlogin(s, command))
1481 #else /* HAVE_OSF_SIA */
1482 /* When PAM is enabled we rely on it to do the nologin check */
1483 if (!options.use_pam)
1485 do_setusercontext(pw);
1487 * PAM session modules in do_setusercontext may have
1488 * generated messages, so if this in an interactive
1489 * login then display them too.
1491 if (!check_quietlogin(s, command))
1493 #endif /* HAVE_OSF_SIA */
1497 if (options.use_pam && !options.use_login && !is_pam_session_open()) {
1498 debug3("PAM session not opened, exiting");
1505 * Get the shell from the password data. An empty shell field is
1506 * legal, and means /bin/sh.
1508 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1511 * Make sure $SHELL points to the shell from the password file,
1512 * even if shell is overridden from login.conf
1514 env = do_setup_env(s, shell);
1516 #ifdef HAVE_LOGIN_CAP
1517 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1520 /* we have to stash the hostname before we close our socket. */
1521 if (options.use_login)
1522 hostname = get_remote_name_or_ip(utmp_len,
1525 * Close the connection descriptors; note that this is the child, and
1526 * the server will still have the socket open, and it is important
1527 * that we do not shutdown it. Note that the descriptors cannot be
1528 * closed before building the environment, as we call
1529 * get_remote_ipaddr there.
1534 * Must take new environment into use so that .ssh/rc,
1535 * /etc/ssh/sshrc and xauth are run in the proper environment.
1539 #if defined(KRB5) && defined(USE_AFS)
1541 * At this point, we check to see if AFS is active and if we have
1542 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1543 * if we can (and need to) extend the ticket into an AFS token. If
1544 * we don't do this, we run into potential problems if the user's
1545 * home directory is in AFS and it's not world-readable.
1548 if (options.kerberos_get_afs_token && k_hasafs() &&
1549 (s->authctxt->krb5_ctx != NULL)) {
1552 debug("Getting AFS token");
1556 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1557 krb5_afslog(s->authctxt->krb5_ctx,
1558 s->authctxt->krb5_fwd_ccache, cell, NULL);
1560 krb5_afslog_home(s->authctxt->krb5_ctx,
1561 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1565 /* Change current directory to the user's home directory. */
1566 if (chdir(pw->pw_dir) < 0) {
1567 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1568 pw->pw_dir, strerror(errno));
1569 #ifdef HAVE_LOGIN_CAP
1570 if (login_getcapbool(lc, "requirehome", 0))
1575 if (!options.use_login)
1576 do_rc_files(s, shell);
1578 /* restore SIGPIPE for child */
1579 signal(SIGPIPE, SIG_DFL);
1581 if (options.use_login) {
1582 launch_login(pw, hostname);
1586 /* Get the last component of the shell name. */
1587 if ((shell0 = strrchr(shell, '/')) != NULL)
1593 * If we have no command, execute the shell. In this case, the shell
1594 * name to be passed in argv[0] is preceded by '-' to indicate that
1595 * this is a login shell.
1600 /* Start the shell. Set initial character to '-'. */
1603 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1604 >= sizeof(argv0) - 1) {
1610 /* Execute the shell. */
1613 execve(shell, argv, env);
1615 /* Executing the shell failed. */
1620 * Execute the command using the user's shell. This uses the -c
1621 * option to execute the command.
1623 argv[0] = (char *) shell0;
1625 argv[2] = (char *) command;
1627 execve(shell, argv, env);
1636 static int did_init = 0;
1638 debug("session_new: init");
1639 for (i = 0; i < MAX_SESSIONS; i++) {
1640 sessions[i].used = 0;
1644 for (i = 0; i < MAX_SESSIONS; i++) {
1645 Session *s = &sessions[i];
1647 memset(s, 0, sizeof(*s));
1653 s->x11_chanids = NULL;
1654 debug("session_new: session %d", i);
1665 for (i = 0; i < MAX_SESSIONS; i++) {
1666 Session *s = &sessions[i];
1667 debug("dump: used %d session %d %p channel %d pid %ld",
1677 session_open(Authctxt *authctxt, int chanid)
1679 Session *s = session_new();
1680 debug("session_open: channel %d", chanid);
1682 error("no more sessions");
1685 s->authctxt = authctxt;
1686 s->pw = authctxt->pw;
1687 if (s->pw == NULL || !authctxt->valid)
1688 fatal("no user for session %d", s->self);
1689 debug("session_open: session %d: link with channel %d", s->self, chanid);
1695 session_by_tty(char *tty)
1698 for (i = 0; i < MAX_SESSIONS; i++) {
1699 Session *s = &sessions[i];
1700 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1701 debug("session_by_tty: session %d tty %s", i, tty);
1705 debug("session_by_tty: unknown tty %.100s", tty);
1711 session_by_channel(int id)
1714 for (i = 0; i < MAX_SESSIONS; i++) {
1715 Session *s = &sessions[i];
1716 if (s->used && s->chanid == id) {
1717 debug("session_by_channel: session %d channel %d", i, id);
1721 debug("session_by_channel: unknown channel %d", id);
1727 session_by_x11_channel(int id)
1731 for (i = 0; i < MAX_SESSIONS; i++) {
1732 Session *s = &sessions[i];
1734 if (s->x11_chanids == NULL || !s->used)
1736 for (j = 0; s->x11_chanids[j] != -1; j++) {
1737 if (s->x11_chanids[j] == id) {
1738 debug("session_by_x11_channel: session %d "
1739 "channel %d", s->self, id);
1744 debug("session_by_x11_channel: unknown channel %d", id);
1750 session_by_pid(pid_t pid)
1753 debug("session_by_pid: pid %ld", (long)pid);
1754 for (i = 0; i < MAX_SESSIONS; i++) {
1755 Session *s = &sessions[i];
1756 if (s->used && s->pid == pid)
1759 error("session_by_pid: unknown pid %ld", (long)pid);
1765 session_window_change_req(Session *s)
1767 s->col = packet_get_int();
1768 s->row = packet_get_int();
1769 s->xpixel = packet_get_int();
1770 s->ypixel = packet_get_int();
1772 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1777 session_pty_req(Session *s)
1783 debug("Allocating a pty not permitted for this authentication.");
1786 if (s->ttyfd != -1) {
1787 packet_disconnect("Protocol error: you already have a pty.");
1791 s->term = packet_get_string(&len);
1794 s->col = packet_get_int();
1795 s->row = packet_get_int();
1797 s->row = packet_get_int();
1798 s->col = packet_get_int();
1800 s->xpixel = packet_get_int();
1801 s->ypixel = packet_get_int();
1803 if (strcmp(s->term, "") == 0) {
1808 /* Allocate a pty and open it. */
1809 debug("Allocating pty.");
1810 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1816 error("session_pty_req: session %d alloc failed", s->self);
1819 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1821 /* for SSH1 the tty modes length is not given */
1823 n_bytes = packet_remaining();
1824 tty_parse_modes(s->ttyfd, &n_bytes);
1827 pty_setowner(s->pw, s->tty);
1829 /* Set window size from the packet. */
1830 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1833 session_proctitle(s);
1838 session_subsystem_req(Session *s)
1843 char *cmd, *subsys = packet_get_string(&len);
1847 logit("subsystem request for %.100s", subsys);
1849 for (i = 0; i < options.num_subsystems; i++) {
1850 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1851 cmd = options.subsystem_command[i];
1852 if (stat(cmd, &st) < 0) {
1853 error("subsystem: cannot stat %s: %s", cmd,
1857 debug("subsystem: exec() %s", cmd);
1858 s->is_subsystem = 1;
1866 logit("subsystem request for %.100s failed, subsystem not found",
1874 session_x11_req(Session *s)
1878 if (s->auth_proto != NULL || s->auth_data != NULL) {
1879 error("session_x11_req: session %d: "
1880 "x11 forwarding already active", s->self);
1883 s->single_connection = packet_get_char();
1884 s->auth_proto = packet_get_string(NULL);
1885 s->auth_data = packet_get_string(NULL);
1886 s->screen = packet_get_int();
1889 success = session_setup_x11fwd(s);
1891 xfree(s->auth_proto);
1892 xfree(s->auth_data);
1893 s->auth_proto = NULL;
1894 s->auth_data = NULL;
1900 session_shell_req(Session *s)
1908 session_exec_req(Session *s)
1911 char *command = packet_get_string(&len);
1913 do_exec(s, command);
1919 session_break_req(Session *s)
1922 packet_get_int(); /* ignored */
1925 if (s->ttyfd == -1 ||
1926 tcsendbreak(s->ttyfd, 0) < 0)
1932 session_env_req(Session *s)
1935 u_int name_len, val_len, i;
1937 name = packet_get_string(&name_len);
1938 val = packet_get_string(&val_len);
1941 /* Don't set too many environment variables */
1942 if (s->num_env > 128) {
1943 debug2("Ignoring env request %s: too many env vars", name);
1947 for (i = 0; i < options.num_accept_env; i++) {
1948 if (match_pattern(name, options.accept_env[i])) {
1949 debug2("Setting env %d: %s=%s", s->num_env, name, val);
1950 s->env = xrealloc(s->env, s->num_env + 1,
1952 s->env[s->num_env].name = name;
1953 s->env[s->num_env].val = val;
1958 debug2("Ignoring env request %s: disallowed name", name);
1967 session_auth_agent_req(Session *s)
1969 static int called = 0;
1971 if (no_agent_forwarding_flag) {
1972 debug("session_auth_agent_req: no_agent_forwarding_flag");
1979 return auth_input_request_forwarding(s->pw);
1984 session_input_channel_req(Channel *c, const char *rtype)
1989 if ((s = session_by_channel(c->self)) == NULL) {
1990 logit("session_input_channel_req: no session %d req %.100s",
1994 debug("session_input_channel_req: session %d req %s", s->self, rtype);
1997 * a session is in LARVAL state until a shell, a command
1998 * or a subsystem is executed
2000 if (c->type == SSH_CHANNEL_LARVAL) {
2001 if (strcmp(rtype, "shell") == 0) {
2002 success = session_shell_req(s);
2003 } else if (strcmp(rtype, "exec") == 0) {
2004 success = session_exec_req(s);
2005 } else if (strcmp(rtype, "pty-req") == 0) {
2006 success = session_pty_req(s);
2007 } else if (strcmp(rtype, "x11-req") == 0) {
2008 success = session_x11_req(s);
2009 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2010 success = session_auth_agent_req(s);
2011 } else if (strcmp(rtype, "subsystem") == 0) {
2012 success = session_subsystem_req(s);
2013 } else if (strcmp(rtype, "env") == 0) {
2014 success = session_env_req(s);
2017 if (strcmp(rtype, "window-change") == 0) {
2018 success = session_window_change_req(s);
2019 } else if (strcmp(rtype, "break") == 0) {
2020 success = session_break_req(s);
2027 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2030 fatal("session_set_fds: called for proto != 2.0");
2032 * now that have a child and a pipe to the child,
2033 * we can activate our channel and register the fd's
2035 if (s->chanid == -1)
2036 fatal("no channel for session %d", s->self);
2037 channel_set_fds(s->chanid,
2039 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2041 CHAN_SES_WINDOW_DEFAULT);
2045 * Function to perform pty cleanup. Also called if we get aborted abnormally
2046 * (e.g., due to a dropped connection).
2049 session_pty_cleanup2(Session *s)
2052 error("session_pty_cleanup: no session");
2058 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2060 /* Record that the user has logged out. */
2062 record_logout(s->pid, s->tty, s->pw->pw_name);
2064 /* Release the pseudo-tty. */
2066 pty_release(s->tty);
2069 * Close the server side of the socket pairs. We must do this after
2070 * the pty cleanup, so that another process doesn't get this pty
2071 * while we're still cleaning up.
2073 if (close(s->ptymaster) < 0)
2074 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2076 /* unlink pty from session */
2081 session_pty_cleanup(Session *s)
2083 PRIVSEP(session_pty_cleanup2(s));
2089 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2104 return "SIG@openssh.com";
2108 session_close_x11(int id)
2112 if ((c = channel_by_id(id)) == NULL) {
2113 debug("session_close_x11: x11 channel %d missing", id);
2115 /* Detach X11 listener */
2116 debug("session_close_x11: detach x11 channel %d", id);
2117 channel_cancel_cleanup(id);
2118 if (c->ostate != CHAN_OUTPUT_CLOSED)
2124 session_close_single_x11(int id, void *arg)
2129 debug3("session_close_single_x11: channel %d", id);
2130 channel_cancel_cleanup(id);
2131 if ((s = session_by_x11_channel(id)) == NULL)
2132 fatal("session_close_single_x11: no x11 channel %d", id);
2133 for (i = 0; s->x11_chanids[i] != -1; i++) {
2134 debug("session_close_single_x11: session %d: "
2135 "closing channel %d", s->self, s->x11_chanids[i]);
2137 * The channel "id" is already closing, but make sure we
2138 * close all of its siblings.
2140 if (s->x11_chanids[i] != id)
2141 session_close_x11(s->x11_chanids[i]);
2143 xfree(s->x11_chanids);
2144 s->x11_chanids = NULL;
2149 if (s->auth_proto) {
2150 xfree(s->auth_proto);
2151 s->auth_proto = NULL;
2154 xfree(s->auth_data);
2155 s->auth_data = NULL;
2157 if (s->auth_display) {
2158 xfree(s->auth_display);
2159 s->auth_display = NULL;
2164 session_exit_message(Session *s, int status)
2168 if ((c = channel_lookup(s->chanid)) == NULL)
2169 fatal("session_exit_message: session %d: no channel %d",
2170 s->self, s->chanid);
2171 debug("session_exit_message: session %d channel %d pid %ld",
2172 s->self, s->chanid, (long)s->pid);
2174 if (WIFEXITED(status)) {
2175 channel_request_start(s->chanid, "exit-status", 0);
2176 packet_put_int(WEXITSTATUS(status));
2178 } else if (WIFSIGNALED(status)) {
2179 channel_request_start(s->chanid, "exit-signal", 0);
2180 packet_put_cstring(sig2name(WTERMSIG(status)));
2182 packet_put_char(WCOREDUMP(status));
2183 #else /* WCOREDUMP */
2185 #endif /* WCOREDUMP */
2186 packet_put_cstring("");
2187 packet_put_cstring("");
2190 /* Some weird exit cause. Just exit. */
2191 packet_disconnect("wait returned status %04x.", status);
2194 /* disconnect channel */
2195 debug("session_exit_message: release channel %d", s->chanid);
2198 * Adjust cleanup callback attachment to send close messages when
2199 * the channel gets EOF. The session will be then be closed
2200 * by session_close_by_channel when the childs close their fds.
2202 channel_register_cleanup(c->self, session_close_by_channel, 1);
2205 * emulate a write failure with 'chan_write_failed', nobody will be
2206 * interested in data we write.
2207 * Note that we must not call 'chan_read_failed', since there could
2208 * be some more data waiting in the pipe.
2210 if (c->ostate != CHAN_OUTPUT_CLOSED)
2211 chan_write_failed(c);
2215 session_close(Session *s)
2219 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2221 session_pty_cleanup(s);
2227 xfree(s->x11_chanids);
2228 if (s->auth_display)
2229 xfree(s->auth_display);
2231 xfree(s->auth_data);
2233 xfree(s->auth_proto);
2235 for (i = 0; i < s->num_env; i++) {
2236 xfree(s->env[i].name);
2237 xfree(s->env[i].val);
2241 session_proctitle(s);
2245 session_close_by_pid(pid_t pid, int status)
2247 Session *s = session_by_pid(pid);
2249 debug("session_close_by_pid: no session for pid %ld",
2253 if (s->chanid != -1)
2254 session_exit_message(s, status);
2256 session_pty_cleanup(s);
2261 * this is called when a channel dies before
2262 * the session 'child' itself dies
2265 session_close_by_channel(int id, void *arg)
2267 Session *s = session_by_channel(id);
2271 debug("session_close_by_channel: no session for id %d", id);
2274 debug("session_close_by_channel: channel %d child %ld",
2277 debug("session_close_by_channel: channel %d: has child", id);
2279 * delay detach of session, but release pty, since
2280 * the fd's to the child are already closed
2283 session_pty_cleanup(s);
2286 /* detach by removing callback */
2287 channel_cancel_cleanup(s->chanid);
2289 /* Close any X11 listeners associated with this session */
2290 if (s->x11_chanids != NULL) {
2291 for (i = 0; s->x11_chanids[i] != -1; i++) {
2292 session_close_x11(s->x11_chanids[i]);
2293 s->x11_chanids[i] = -1;
2302 session_destroy_all(void (*closefunc)(Session *))
2305 for (i = 0; i < MAX_SESSIONS; i++) {
2306 Session *s = &sessions[i];
2308 if (closefunc != NULL)
2317 session_tty_list(void)
2319 static char buf[1024];
2324 for (i = 0; i < MAX_SESSIONS; i++) {
2325 Session *s = &sessions[i];
2326 if (s->used && s->ttyfd != -1) {
2328 if (strncmp(s->tty, "/dev/", 5) != 0) {
2329 cp = strrchr(s->tty, '/');
2330 cp = (cp == NULL) ? s->tty : cp + 1;
2335 strlcat(buf, ",", sizeof buf);
2336 strlcat(buf, cp, sizeof buf);
2340 strlcpy(buf, "notty", sizeof buf);
2345 session_proctitle(Session *s)
2348 error("no user for session %d", s->self);
2350 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2354 session_setup_x11fwd(Session *s)
2357 char display[512], auth_display[512];
2358 char hostname[MAXHOSTNAMELEN];
2361 if (no_x11_forwarding_flag) {
2362 packet_send_debug("X11 forwarding disabled in user configuration file.");
2365 if (!options.x11_forwarding) {
2366 debug("X11 forwarding disabled in server configuration file.");
2369 if (!options.xauth_location ||
2370 (stat(options.xauth_location, &st) == -1)) {
2371 packet_send_debug("No xauth program; cannot forward with spoofing.");
2374 if (options.use_login) {
2375 packet_send_debug("X11 forwarding disabled; "
2376 "not compatible with UseLogin=yes.");
2379 if (s->display != NULL) {
2380 debug("X11 display already set.");
2383 if (x11_create_display_inet(options.x11_display_offset,
2384 options.x11_use_localhost, s->single_connection,
2385 &s->display_number, &s->x11_chanids) == -1) {
2386 debug("x11_create_display_inet failed.");
2389 for (i = 0; s->x11_chanids[i] != -1; i++) {
2390 channel_register_cleanup(s->x11_chanids[i],
2391 session_close_single_x11, 0);
2394 /* Set up a suitable value for the DISPLAY variable. */
2395 if (gethostname(hostname, sizeof(hostname)) < 0)
2396 fatal("gethostname: %.100s", strerror(errno));
2398 * auth_display must be used as the displayname when the
2399 * authorization entry is added with xauth(1). This will be
2400 * different than the DISPLAY string for localhost displays.
2402 if (options.x11_use_localhost) {
2403 snprintf(display, sizeof display, "localhost:%u.%u",
2404 s->display_number, s->screen);
2405 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2406 s->display_number, s->screen);
2407 s->display = xstrdup(display);
2408 s->auth_display = xstrdup(auth_display);
2410 #ifdef IPADDR_IN_DISPLAY
2412 struct in_addr my_addr;
2414 he = gethostbyname(hostname);
2416 error("Can't get IP address for X11 DISPLAY.");
2417 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2420 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2421 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2422 s->display_number, s->screen);
2424 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2425 s->display_number, s->screen);
2427 s->display = xstrdup(display);
2428 s->auth_display = xstrdup(display);
2435 do_authenticated2(Authctxt *authctxt)
2437 server_loop2(authctxt);
2441 do_cleanup(Authctxt *authctxt)
2443 static int called = 0;
2445 debug("do_cleanup");
2447 /* no cleanup if we're in the child for login shell */
2451 /* avoid double cleanup */
2456 if (authctxt == NULL)
2459 if (options.kerberos_ticket_cleanup &&
2461 krb5_cleanup_proc(authctxt);
2465 if (compat20 && options.gss_cleanup_creds)
2466 ssh_gssapi_cleanup_creds();
2470 if (options.use_pam) {
2472 sshpam_thread_cleanup();
2476 /* remove agent socket */
2477 auth_sock_cleanup_proc(authctxt->pw);
2480 * Cleanup ptys/utmp only if privsep is disabled,
2481 * or if running in monitor.
2483 if (!use_privsep || mm_is_monitor())
2484 session_destroy_all(session_pty_cleanup2);