2 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * As far as I am concerned, the code I have written for this software
6 * can be used freely for any purpose. Any derived versions of this
7 * software must be clearly marked as such, and if the derived work is
8 * incompatible with the protocol description in the RFC file, it must be
9 * called by a name other than "ssh" or "Secure Shell".
11 * SSH2 support by Markus Friedl.
12 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 RCSID("$OpenBSD: session.c,v 1.164 2003/09/18 08:49:45 markus Exp $");
52 #include "auth-options.h"
53 #include "pathnames.h"
57 #include "serverloop.h"
60 #include "monitor_wrap.h"
68 Session *session_new(void);
69 void session_set_fds(Session *, int, int, int);
70 void session_pty_cleanup(void *);
71 void session_proctitle(Session *);
72 int session_setup_x11fwd(Session *);
73 void do_exec_pty(Session *, const char *);
74 void do_exec_no_pty(Session *, const char *);
75 void do_exec(Session *, const char *);
76 void do_login(Session *, const char *);
77 #ifdef LOGIN_NEEDS_UTMPX
78 static void do_pre_login(Session *s);
80 void do_child(Session *, const char *);
82 int check_quietlogin(Session *, const char *);
84 static void do_authenticated1(Authctxt *);
85 static void do_authenticated2(Authctxt *);
87 static int session_pty_req(Session *);
90 extern ServerOptions options;
91 extern char *__progname;
92 extern int log_stderr;
93 extern int debug_flag;
94 extern u_int utmp_len;
95 extern int startup_pipe;
96 extern void destroy_sensitive_data(void);
97 extern Buffer loginmsg;
99 /* original command from peer. */
100 const char *original_command = NULL;
103 #define MAX_SESSIONS 10
104 Session sessions[MAX_SESSIONS];
106 #ifdef HAVE_LOGIN_CAP
110 /* Name and directory of socket for authentication agent forwarding. */
111 static char *auth_sock_name = NULL;
112 static char *auth_sock_dir = NULL;
114 /* removes the agent forwarding socket */
117 auth_sock_cleanup_proc(void *_pw)
119 struct passwd *pw = _pw;
121 if (auth_sock_name != NULL) {
122 temporarily_use_uid(pw);
123 unlink(auth_sock_name);
124 rmdir(auth_sock_dir);
125 auth_sock_name = NULL;
131 auth_input_request_forwarding(struct passwd * pw)
135 struct sockaddr_un sunaddr;
137 if (auth_sock_name != NULL) {
138 error("authentication forwarding requested twice.");
142 /* Temporarily drop privileged uid for mkdir/bind. */
143 temporarily_use_uid(pw);
145 /* Allocate a buffer for the socket name, and format the name. */
146 auth_sock_name = xmalloc(MAXPATHLEN);
147 auth_sock_dir = xmalloc(MAXPATHLEN);
148 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
150 /* Create private directory for socket */
151 if (mkdtemp(auth_sock_dir) == NULL) {
152 packet_send_debug("Agent forwarding disabled: "
153 "mkdtemp() failed: %.100s", strerror(errno));
155 xfree(auth_sock_name);
156 xfree(auth_sock_dir);
157 auth_sock_name = NULL;
158 auth_sock_dir = NULL;
161 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
162 auth_sock_dir, (long) getpid());
164 /* delete agent socket on fatal() */
165 fatal_add_cleanup(auth_sock_cleanup_proc, pw);
167 /* Create the socket. */
168 sock = socket(AF_UNIX, SOCK_STREAM, 0);
170 packet_disconnect("socket: %.100s", strerror(errno));
172 /* Bind it to the name. */
173 memset(&sunaddr, 0, sizeof(sunaddr));
174 sunaddr.sun_family = AF_UNIX;
175 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
177 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
178 packet_disconnect("bind: %.100s", strerror(errno));
180 /* Restore the privileged uid. */
183 /* Start listening on the socket. */
184 if (listen(sock, 5) < 0)
185 packet_disconnect("listen: %.100s", strerror(errno));
187 /* Allocate a channel for the authentication agent socket. */
188 nc = channel_new("auth socket",
189 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
190 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
191 0, "auth socket", 1);
192 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
198 do_authenticated(Authctxt *authctxt)
200 setproctitle("%s", authctxt->pw->pw_name);
203 * Cancel the alarm we set to limit the time taken for
207 if (startup_pipe != -1) {
212 /* setup the channel layer */
213 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
214 channel_permit_all_opens();
217 do_authenticated2(authctxt);
219 do_authenticated1(authctxt);
221 /* remove agent socket */
222 if (auth_sock_name != NULL)
223 auth_sock_cleanup_proc(authctxt->pw);
225 if (options.kerberos_ticket_cleanup)
226 krb5_cleanup_proc(authctxt);
231 * Prepares for an interactive session. This is called after the user has
232 * been successfully authenticated. During this message exchange, pseudo
233 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
234 * are requested, etc.
237 do_authenticated1(Authctxt *authctxt)
241 int success, type, screen_flag;
242 int enable_compression_after_reply = 0;
243 u_int proto_len, data_len, dlen, compression_level = 0;
246 s->authctxt = authctxt;
247 s->pw = authctxt->pw;
250 * We stay in this loop until the client requests to execute a shell
256 /* Get a packet from the client. */
257 type = packet_read();
259 /* Process the packet. */
261 case SSH_CMSG_REQUEST_COMPRESSION:
262 compression_level = packet_get_int();
264 if (compression_level < 1 || compression_level > 9) {
265 packet_send_debug("Received illegal compression level %d.",
269 if (!options.compression) {
270 debug2("compression disabled");
273 /* Enable compression after we have responded with SUCCESS. */
274 enable_compression_after_reply = 1;
278 case SSH_CMSG_REQUEST_PTY:
279 success = session_pty_req(s);
282 case SSH_CMSG_X11_REQUEST_FORWARDING:
283 s->auth_proto = packet_get_string(&proto_len);
284 s->auth_data = packet_get_string(&data_len);
286 screen_flag = packet_get_protocol_flags() &
287 SSH_PROTOFLAG_SCREEN_NUMBER;
288 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
290 if (packet_remaining() == 4) {
292 debug2("Buggy client: "
293 "X11 screen flag missing");
294 s->screen = packet_get_int();
299 success = session_setup_x11fwd(s);
301 xfree(s->auth_proto);
303 s->auth_proto = NULL;
308 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
309 if (no_agent_forwarding_flag || compat13) {
310 debug("Authentication agent forwarding not permitted for this authentication.");
313 debug("Received authentication agent forwarding request.");
314 success = auth_input_request_forwarding(s->pw);
317 case SSH_CMSG_PORT_FORWARD_REQUEST:
318 if (no_port_forwarding_flag) {
319 debug("Port forwarding not permitted for this authentication.");
322 if (!options.allow_tcp_forwarding) {
323 debug("Port forwarding not permitted.");
326 debug("Received TCP/IP port forwarding request.");
327 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
331 case SSH_CMSG_MAX_PACKET_SIZE:
332 if (packet_set_maxsize(packet_get_int()) > 0)
336 case SSH_CMSG_EXEC_SHELL:
337 case SSH_CMSG_EXEC_CMD:
338 if (type == SSH_CMSG_EXEC_CMD) {
339 command = packet_get_string(&dlen);
340 debug("Exec command '%.500s'", command);
352 * Any unknown messages in this phase are ignored,
353 * and a failure message is returned.
355 logit("Unknown packet type received after authentication: %d", type);
357 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
361 /* Enable compression now that we have replied if appropriate. */
362 if (enable_compression_after_reply) {
363 enable_compression_after_reply = 0;
364 packet_start_compression(compression_level);
370 * This is called to fork and execute a command when we have no tty. This
371 * will call do_child from the child, and server_loop from the parent after
372 * setting up file descriptors and such.
375 do_exec_no_pty(Session *s, const char *command)
380 int pin[2], pout[2], perr[2];
381 /* Allocate pipes for communicating with the program. */
382 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
383 packet_disconnect("Could not create pipes: %.100s",
385 #else /* USE_PIPES */
386 int inout[2], err[2];
387 /* Uses socket pairs to communicate with the program. */
388 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
389 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
390 packet_disconnect("Could not create socket pairs: %.100s",
392 #endif /* USE_PIPES */
394 fatal("do_exec_no_pty: no session");
396 session_proctitle(s);
399 if (options.use_pam) {
401 if (is_pam_password_change_required())
402 packet_disconnect("Password change required but no "
407 /* Fork the child. */
408 if ((pid = fork()) == 0) {
409 fatal_remove_all_cleanups();
411 /* Child. Reinitialize the log since the pid has changed. */
412 log_init(__progname, options.log_level, options.log_facility, log_stderr);
415 * Create a new session and process group since the 4.4BSD
416 * setlogin() affects the entire process group.
419 error("setsid failed: %.100s", strerror(errno));
423 * Redirect stdin. We close the parent side of the socket
424 * pair, and make the child side the standard input.
427 if (dup2(pin[0], 0) < 0)
428 perror("dup2 stdin");
431 /* Redirect stdout. */
433 if (dup2(pout[1], 1) < 0)
434 perror("dup2 stdout");
437 /* Redirect stderr. */
439 if (dup2(perr[1], 2) < 0)
440 perror("dup2 stderr");
442 #else /* USE_PIPES */
444 * Redirect stdin, stdout, and stderr. Stdin and stdout will
445 * use the same socket, as some programs (particularly rdist)
446 * seem to depend on it.
450 if (dup2(inout[0], 0) < 0) /* stdin */
451 perror("dup2 stdin");
452 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
453 perror("dup2 stdout");
454 if (dup2(err[0], 2) < 0) /* stderr */
455 perror("dup2 stderr");
456 #endif /* USE_PIPES */
459 cray_init_job(s->pw); /* set up cray jid and tmpdir */
462 /* Do processing for the child (exec command etc). */
463 do_child(s, command);
467 signal(WJSIGNAL, cray_job_termination_handler);
471 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
474 packet_disconnect("fork failed: %.100s", strerror(errno));
476 /* Set interactive/non-interactive mode. */
477 packet_set_interactive(s->display != NULL);
479 /* We are the parent. Close the child sides of the pipes. */
485 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
487 /* Enter the interactive session. */
488 server_loop(pid, pin[1], pout[0], perr[0]);
489 /* server_loop has closed pin[1], pout[0], and perr[0]. */
491 #else /* USE_PIPES */
492 /* We are the parent. Close the child sides of the socket pairs. */
497 * Enter the interactive session. Note: server_loop must be able to
498 * handle the case that fdin and fdout are the same.
501 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
503 server_loop(pid, inout[1], inout[1], err[1]);
504 /* server_loop has closed inout[1] and err[1]. */
506 #endif /* USE_PIPES */
510 * This is called to fork and execute a command when we have a tty. This
511 * will call do_child from the child, and server_loop from the parent after
512 * setting up file descriptors, controlling tty, updating wtmp, utmp,
513 * lastlog, and other such operations.
516 do_exec_pty(Session *s, const char *command)
518 int fdout, ptyfd, ttyfd, ptymaster;
522 fatal("do_exec_pty: no session");
527 if (options.use_pam) {
528 do_pam_set_tty(s->tty);
533 /* Fork the child. */
534 if ((pid = fork()) == 0) {
535 fatal_remove_all_cleanups();
537 /* Child. Reinitialize the log because the pid has changed. */
538 log_init(__progname, options.log_level, options.log_facility, log_stderr);
539 /* Close the master side of the pseudo tty. */
542 /* Make the pseudo tty our controlling tty. */
543 pty_make_controlling_tty(&ttyfd, s->tty);
545 /* Redirect stdin/stdout/stderr from the pseudo tty. */
546 if (dup2(ttyfd, 0) < 0)
547 error("dup2 stdin: %s", strerror(errno));
548 if (dup2(ttyfd, 1) < 0)
549 error("dup2 stdout: %s", strerror(errno));
550 if (dup2(ttyfd, 2) < 0)
551 error("dup2 stderr: %s", strerror(errno));
553 /* Close the extra descriptor for the pseudo tty. */
556 /* record login, etc. similar to login(1) */
558 if (!(options.use_login && command == NULL)) {
560 cray_init_job(s->pw); /* set up cray jid and tmpdir */
562 do_login(s, command);
564 # ifdef LOGIN_NEEDS_UTMPX
570 /* Do common processing for the child, such as execing the command. */
571 do_child(s, command);
575 signal(WJSIGNAL, cray_job_termination_handler);
579 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
582 packet_disconnect("fork failed: %.100s", strerror(errno));
585 /* Parent. Close the slave side of the pseudo tty. */
589 * Create another descriptor of the pty master side for use as the
590 * standard input. We could use the original descriptor, but this
591 * simplifies code in server_loop. The descriptor is bidirectional.
595 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
597 /* we keep a reference to the pty master */
598 ptymaster = dup(ptyfd);
600 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
601 s->ptymaster = ptymaster;
603 /* Enter interactive session. */
604 packet_set_interactive(1);
606 session_set_fds(s, ptyfd, fdout, -1);
608 server_loop(pid, ptyfd, fdout, -1);
609 /* server_loop _has_ closed ptyfd and fdout. */
613 #ifdef LOGIN_NEEDS_UTMPX
615 do_pre_login(Session *s)
618 struct sockaddr_storage from;
619 pid_t pid = getpid();
622 * Get IP address of client. If the connection is not a socket, let
623 * the address be 0.0.0.0.
625 memset(&from, 0, sizeof(from));
626 fromlen = sizeof(from);
627 if (packet_connection_is_on_socket()) {
628 if (getpeername(packet_get_connection_in(),
629 (struct sockaddr *) & from, &fromlen) < 0) {
630 debug("getpeername: %.100s", strerror(errno));
635 record_utmp_only(pid, s->tty, s->pw->pw_name,
636 get_remote_name_or_ip(utmp_len, options.use_dns),
637 (struct sockaddr *)&from, fromlen);
642 * This is called to fork and execute a command. If another command is
643 * to be forced, execute that instead.
646 do_exec(Session *s, const char *command)
648 if (forced_command) {
649 original_command = command;
650 command = forced_command;
651 debug("Forced command '%.900s'", command);
655 if (options.gss_authentication) {
656 temporarily_use_uid(s->pw);
657 ssh_gssapi_storecreds();
663 do_exec_pty(s, command);
665 do_exec_no_pty(s, command);
667 original_command = NULL;
671 /* administrative, login(1)-like work */
673 do_login(Session *s, const char *command)
677 struct sockaddr_storage from;
678 struct passwd * pw = s->pw;
679 pid_t pid = getpid();
682 * Get IP address of client. If the connection is not a socket, let
683 * the address be 0.0.0.0.
685 memset(&from, 0, sizeof(from));
686 fromlen = sizeof(from);
687 if (packet_connection_is_on_socket()) {
688 if (getpeername(packet_get_connection_in(),
689 (struct sockaddr *) & from, &fromlen) < 0) {
690 debug("getpeername: %.100s", strerror(errno));
695 /* Record that there was a login on that tty from the remote host. */
697 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
698 get_remote_name_or_ip(utmp_len,
700 (struct sockaddr *)&from, fromlen);
704 * If password change is needed, do it now.
705 * This needs to occur before the ~/.hushlogin check.
707 if (options.use_pam && is_pam_password_change_required()) {
708 print_pam_messages();
710 /* XXX - signal [net] parent to enable forwardings */
714 if (check_quietlogin(s, command))
718 if (options.use_pam && !is_pam_password_change_required())
719 print_pam_messages();
722 /* display post-login message */
723 if (buffer_len(&loginmsg) > 0) {
724 buffer_append(&loginmsg, "\0", 1);
725 printf("%s\n", (char *)buffer_ptr(&loginmsg));
727 buffer_free(&loginmsg);
729 #ifndef NO_SSH_LASTLOG
730 if (options.print_lastlog && s->last_login_time != 0) {
731 time_string = ctime(&s->last_login_time);
732 if (strchr(time_string, '\n'))
733 *strchr(time_string, '\n') = 0;
734 if (strcmp(s->hostname, "") == 0)
735 printf("Last login: %s\r\n", time_string);
737 printf("Last login: %s from %s\r\n", time_string,
740 #endif /* NO_SSH_LASTLOG */
746 * Display the message of the day.
753 #ifdef HAVE_LOGIN_CAP
757 #ifdef HAVE_LOGIN_CAP
758 fname = login_getcapstr(lc, "copyright", NULL, NULL);
759 if (fname != NULL && (f = fopen(fname, "r")) != NULL) {
760 while (fgets(buf, sizeof(buf), f) != NULL)
764 #endif /* HAVE_LOGIN_CAP */
765 (void)printf("%s\n\t%s %s\n",
766 "Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
767 "The Regents of the University of California. ",
768 "All rights reserved.");
772 if (options.print_motd) {
773 #ifdef HAVE_LOGIN_CAP
774 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
777 f = fopen("/etc/motd", "r");
780 while (fgets(buf, sizeof(buf), f))
789 * Check for quiet login, either .hushlogin or command given.
792 check_quietlogin(Session *s, const char *command)
795 struct passwd *pw = s->pw;
798 /* Return 1 if .hushlogin exists or a command given. */
801 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
802 #ifdef HAVE_LOGIN_CAP
803 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
806 if (stat(buf, &st) >= 0)
813 * Sets the value of the given variable in the environment. If the variable
814 * already exists, its value is overriden.
817 child_set_env(char ***envp, u_int *envsizep, const char *name,
825 * If we're passed an uninitialized list, allocate a single null
826 * entry before continuing.
828 if (*envp == NULL && *envsizep == 0) {
829 *envp = xmalloc(sizeof(char *));
835 * Find the slot where the value should be stored. If the variable
836 * already exists, we reuse the slot; otherwise we append a new slot
837 * at the end of the array, expanding if necessary.
840 namelen = strlen(name);
841 for (i = 0; env[i]; i++)
842 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
845 /* Reuse the slot. */
848 /* New variable. Expand if necessary. */
850 if (i >= envsize - 1) {
852 fatal("child_set_env: too many env vars");
854 env = (*envp) = xrealloc(env, envsize * sizeof(char *));
857 /* Need to set the NULL pointer at end of array beyond the new slot. */
861 /* Allocate space and format the variable in the appropriate slot. */
862 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
863 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
867 * Reads environment variables from the given file and adds/overrides them
868 * into the environment. If the file does not exist, this does nothing.
869 * Otherwise, it must consist of empty lines, comments (line starts with '#')
870 * and assignments of the form name=value. No other forms are allowed.
873 read_environment_file(char ***env, u_int *envsize,
874 const char *filename)
881 f = fopen(filename, "r");
885 while (fgets(buf, sizeof(buf), f)) {
887 fatal("Too many lines in environment file %s", filename);
888 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
890 if (!*cp || *cp == '#' || *cp == '\n')
892 if (strchr(cp, '\n'))
893 *strchr(cp, '\n') = '\0';
894 value = strchr(cp, '=');
896 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
901 * Replace the equals sign by nul, and advance value to
906 child_set_env(env, envsize, cp, value);
911 #ifdef HAVE_ETC_DEFAULT_LOGIN
913 * Return named variable from specified environment, or NULL if not present.
916 child_get_env(char **env, const char *name)
922 for (i=0; env[i] != NULL; i++)
923 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
924 return(env[i] + len + 1);
929 * Read /etc/default/login.
930 * We pick up the PATH (or SUPATH for root) and UMASK.
933 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
935 char **tmpenv = NULL, *var;
936 u_int i, tmpenvsize = 0;
940 * We don't want to copy the whole file to the child's environment,
941 * so we use a temporary environment and copy the variables we're
944 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
950 var = child_get_env(tmpenv, "SUPATH");
952 var = child_get_env(tmpenv, "PATH");
954 child_set_env(env, envsize, "PATH", var);
956 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
957 if (sscanf(var, "%5lo", &mask) == 1)
960 for (i = 0; tmpenv[i] != NULL; i++)
964 #endif /* HAVE_ETC_DEFAULT_LOGIN */
966 void copy_environment(char **source, char ***env, u_int *envsize)
968 char *var_name, *var_val;
974 for(i = 0; source[i] != NULL; i++) {
975 var_name = xstrdup(source[i]);
976 if ((var_val = strstr(var_name, "=")) == NULL) {
982 debug3("Copy environment: %s=%s", var_name, var_val);
983 child_set_env(env, envsize, var_name, var_val);
990 do_setup_env(Session *s, const char *shell)
994 char **env, *laddr, *path = NULL;
995 #ifdef HAVE_LOGIN_CAP
996 extern char **environ;
999 struct passwd *pw = s->pw;
1001 /* Initialize the environment. */
1003 env = xmalloc(envsize * sizeof(char *));
1008 * The Windows environment contains some setting which are
1009 * important for a running system. They must not be dropped.
1011 copy_environment(environ, &env, &envsize);
1015 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1018 /* Allow any GSSAPI methods that we've used to alter
1019 * the childs environment as they see fit
1021 ssh_gssapi_do_child(&env, &envsize);
1024 if (!options.use_login) {
1025 /* Set basic environment. */
1026 child_set_env(&env, &envsize, "USER", pw->pw_name);
1027 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1029 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1031 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1032 snprintf(buf, sizeof buf, "%.200s/%.50s",
1033 _PATH_MAILDIR, pw->pw_name);
1034 child_set_env(&env, &envsize, "MAIL", buf);
1035 #ifdef HAVE_LOGIN_CAP
1036 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1037 child_set_env(&env, &envsize, "TERM", "su");
1039 environ = xmalloc(sizeof(char *));
1041 (void) setusercontext(lc, pw, pw->pw_uid,
1042 LOGIN_SETENV|LOGIN_SETPATH);
1043 copy_environment(environ, &env, &envsize);
1044 for (var = environ; *var != NULL; ++var)
1048 #else /* HAVE_LOGIN_CAP */
1049 # ifndef HAVE_CYGWIN
1051 * There's no standard path on Windows. The path contains
1052 * important components pointing to the system directories,
1053 * needed for loading shared libraries. So the path better
1054 * remains intact here.
1056 # ifdef HAVE_ETC_DEFAULT_LOGIN
1057 read_etc_default_login(&env, &envsize, pw->pw_uid);
1058 path = child_get_env(env, "PATH");
1059 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1060 if (path == NULL || *path == '\0') {
1061 child_set_env(&env, &envsize, "PATH",
1062 s->pw->pw_uid == 0 ?
1063 SUPERUSER_PATH : _PATH_STDPATH);
1065 # endif /* HAVE_CYGWIN */
1066 #endif /* HAVE_LOGIN_CAP */
1068 /* Normal systems set SHELL by default. */
1069 child_set_env(&env, &envsize, "SHELL", shell);
1072 /* Set custom environment options from RSA authentication. */
1073 if (!options.use_login) {
1074 while (custom_environment) {
1075 struct envstring *ce = custom_environment;
1078 for (i = 0; str[i] != '=' && str[i]; i++)
1080 if (str[i] == '=') {
1082 child_set_env(&env, &envsize, str, str + i + 1);
1084 custom_environment = ce->next;
1090 /* SSH_CLIENT deprecated */
1091 snprintf(buf, sizeof buf, "%.50s %d %d",
1092 get_remote_ipaddr(), get_remote_port(), get_local_port());
1093 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1095 laddr = get_local_ipaddr(packet_get_connection_in());
1096 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1097 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1099 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1102 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1104 child_set_env(&env, &envsize, "TERM", s->term);
1106 child_set_env(&env, &envsize, "DISPLAY", s->display);
1107 if (original_command)
1108 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1112 if (cray_tmpdir[0] != '\0')
1113 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1114 #endif /* _UNICOS */
1120 if ((cp = getenv("AUTHSTATE")) != NULL)
1121 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1122 if ((cp = getenv("KRB5CCNAME")) != NULL)
1123 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1124 read_environment_file(&env, &envsize, "/etc/environment");
1128 if (s->authctxt->krb5_ticket_file)
1129 child_set_env(&env, &envsize, "KRB5CCNAME",
1130 s->authctxt->krb5_ticket_file);
1134 * Pull in any environment variables that may have
1137 if (options.use_pam) {
1138 char **p = fetch_pam_environment();
1140 copy_environment(p, &env, &envsize);
1141 free_pam_environment(p);
1143 #endif /* USE_PAM */
1145 if (auth_sock_name != NULL)
1146 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1149 /* read $HOME/.ssh/environment. */
1150 if (options.permit_user_env && !options.use_login) {
1151 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1152 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1153 read_environment_file(&env, &envsize, buf);
1156 /* dump the environment */
1157 fprintf(stderr, "Environment:\n");
1158 for (i = 0; env[i]; i++)
1159 fprintf(stderr, " %.200s\n", env[i]);
1165 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1166 * first in this order).
1169 do_rc_files(Session *s, const char *shell)
1177 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1179 /* ignore _PATH_SSH_USER_RC for subsystems */
1180 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1181 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1182 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1184 fprintf(stderr, "Running %s\n", cmd);
1185 f = popen(cmd, "w");
1188 fprintf(f, "%s %s\n", s->auth_proto,
1192 fprintf(stderr, "Could not run %s\n",
1194 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1196 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1197 _PATH_SSH_SYSTEM_RC);
1198 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1201 fprintf(f, "%s %s\n", s->auth_proto,
1205 fprintf(stderr, "Could not run %s\n",
1206 _PATH_SSH_SYSTEM_RC);
1207 } else if (do_xauth && options.xauth_location != NULL) {
1208 /* Add authority data to .Xauthority if appropriate. */
1211 "Running %.500s remove %.100s\n",
1212 options.xauth_location, s->auth_display);
1214 "%.500s add %.100s %.100s %.100s\n",
1215 options.xauth_location, s->auth_display,
1216 s->auth_proto, s->auth_data);
1218 snprintf(cmd, sizeof cmd, "%s -q -",
1219 options.xauth_location);
1220 f = popen(cmd, "w");
1222 fprintf(f, "remove %s\n",
1224 fprintf(f, "add %s %s %s\n",
1225 s->auth_display, s->auth_proto,
1229 fprintf(stderr, "Could not run %s\n",
1236 do_nologin(struct passwd *pw)
1241 #ifdef HAVE_LOGIN_CAP
1242 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1243 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1244 _PATH_NOLOGIN), "r");
1247 f = fopen(_PATH_NOLOGIN, "r");
1250 /* /etc/nologin exists. Print its contents and exit. */
1251 logit("User %.100s not allowed because %s exists",
1252 pw->pw_name, _PATH_NOLOGIN);
1253 while (fgets(buf, sizeof(buf), f))
1261 /* Set login name, uid, gid, and groups. */
1263 do_setusercontext(struct passwd *pw)
1266 if (getuid() == 0 || geteuid() == 0)
1267 #endif /* HAVE_CYGWIN */
1270 #ifdef HAVE_SETPCRED
1271 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1272 fatal("Failed to set process credentials");
1273 #endif /* HAVE_SETPCRED */
1274 #ifdef HAVE_LOGIN_CAP
1278 if (setusercontext(lc, pw, pw->pw_uid,
1279 (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH))) < 0) {
1280 perror("unable to set user context");
1284 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1285 /* Sets login uid for accounting */
1286 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1287 error("setluid: %s", strerror(errno));
1288 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1290 if (setlogin(pw->pw_name) < 0)
1291 error("setlogin failed: %s", strerror(errno));
1292 if (setgid(pw->pw_gid) < 0) {
1296 /* Initialize the group list. */
1297 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1298 perror("initgroups");
1304 * PAM credentials may take the form of supplementary groups.
1305 * These will have been wiped by the above initgroups() call.
1306 * Reestablish them here.
1308 if (options.use_pam) {
1312 # endif /* USE_PAM */
1313 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1314 irix_setusercontext(pw);
1315 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1319 /* Permanently switch to the desired uid. */
1320 permanently_set_uid(pw);
1327 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1328 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1332 launch_login(struct passwd *pw, const char *hostname)
1334 /* Launch login(1). */
1336 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1337 #ifdef xxxLOGIN_NEEDS_TERM
1338 (s->term ? s->term : "unknown"),
1339 #endif /* LOGIN_NEEDS_TERM */
1340 #ifdef LOGIN_NO_ENDOPT
1341 "-p", "-f", pw->pw_name, (char *)NULL);
1343 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1346 /* Login couldn't be executed, die. */
1353 * Performs common processing for the child, such as setting up the
1354 * environment, closing extra file descriptors, setting the user and group
1355 * ids, and executing the command or shell.
1358 do_child(Session *s, const char *command)
1360 extern char **environ;
1363 const char *shell, *shell0, *hostname = NULL;
1364 struct passwd *pw = s->pw;
1366 #ifdef HAVE_LOGIN_CAP
1370 /* remove hostkey from the child's memory */
1371 destroy_sensitive_data();
1373 /* login(1) is only called if we execute the login shell */
1374 if (options.use_login && command != NULL)
1375 options.use_login = 0;
1378 cray_setup(pw->pw_uid, pw->pw_name, command);
1379 #endif /* _UNICOS */
1382 * Login(1) does this as well, and it needs uid 0 for the "-h"
1383 * switch, so we let login(1) to this for us.
1385 if (!options.use_login) {
1387 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1388 if (!check_quietlogin(s, command))
1390 #else /* HAVE_OSF_SIA */
1392 do_setusercontext(pw);
1393 #endif /* HAVE_OSF_SIA */
1397 * Get the shell from the password data. An empty shell field is
1398 * legal, and means /bin/sh.
1400 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1403 * Make sure $SHELL points to the shell from the password file,
1404 * even if shell is overridden from login.conf
1406 env = do_setup_env(s, shell);
1408 #ifdef HAVE_LOGIN_CAP
1409 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1412 /* we have to stash the hostname before we close our socket. */
1413 if (options.use_login)
1414 hostname = get_remote_name_or_ip(utmp_len,
1417 * Close the connection descriptors; note that this is the child, and
1418 * the server will still have the socket open, and it is important
1419 * that we do not shutdown it. Note that the descriptors cannot be
1420 * closed before building the environment, as we call
1421 * get_remote_ipaddr there.
1423 if (packet_get_connection_in() == packet_get_connection_out())
1424 close(packet_get_connection_in());
1426 close(packet_get_connection_in());
1427 close(packet_get_connection_out());
1430 * Close all descriptors related to channels. They will still remain
1431 * open in the parent.
1433 /* XXX better use close-on-exec? -markus */
1434 channel_close_all();
1436 #ifdef HAVE_LOGIN_CAP
1437 lc_requirehome = login_getcapbool(lc, "requirehome", 0);
1441 * Close any extra file descriptors. Note that there may still be
1442 * descriptors left by system functions. They will be closed later.
1447 * Close any extra open file descriptors so that we don\'t have them
1448 * hanging around in clients. Note that we want to do this after
1449 * initgroups, because at least on Solaris 2.3 it leaves file
1452 for (i = 3; i < 64; i++)
1456 * Must take new environment into use so that .ssh/rc,
1457 * /etc/ssh/sshrc and xauth are run in the proper environment.
1461 /* Change current directory to the user\'s home directory. */
1462 if (chdir(pw->pw_dir) < 0) {
1463 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1464 pw->pw_dir, strerror(errno));
1465 #ifdef HAVE_LOGIN_CAP
1471 if (!options.use_login)
1472 do_rc_files(s, shell);
1474 /* restore SIGPIPE for child */
1475 signal(SIGPIPE, SIG_DFL);
1477 if (options.use_login) {
1478 launch_login(pw, hostname);
1482 /* Get the last component of the shell name. */
1483 if ((shell0 = strrchr(shell, '/')) != NULL)
1489 * If we have no command, execute the shell. In this case, the shell
1490 * name to be passed in argv[0] is preceded by '-' to indicate that
1491 * this is a login shell.
1496 /* Start the shell. Set initial character to '-'. */
1499 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1500 >= sizeof(argv0) - 1) {
1506 /* Execute the shell. */
1509 execve(shell, argv, env);
1511 /* Executing the shell failed. */
1516 * Execute the command using the user's shell. This uses the -c
1517 * option to execute the command.
1519 argv[0] = (char *) shell0;
1521 argv[2] = (char *) command;
1523 execve(shell, argv, env);
1532 static int did_init = 0;
1534 debug("session_new: init");
1535 for (i = 0; i < MAX_SESSIONS; i++) {
1536 sessions[i].used = 0;
1540 for (i = 0; i < MAX_SESSIONS; i++) {
1541 Session *s = &sessions[i];
1543 memset(s, 0, sizeof(*s));
1549 debug("session_new: session %d", i);
1560 for (i = 0; i < MAX_SESSIONS; i++) {
1561 Session *s = &sessions[i];
1562 debug("dump: used %d session %d %p channel %d pid %ld",
1572 session_open(Authctxt *authctxt, int chanid)
1574 Session *s = session_new();
1575 debug("session_open: channel %d", chanid);
1577 error("no more sessions");
1580 s->authctxt = authctxt;
1581 s->pw = authctxt->pw;
1583 fatal("no user for session %d", s->self);
1584 debug("session_open: session %d: link with channel %d", s->self, chanid);
1590 session_by_tty(char *tty)
1593 for (i = 0; i < MAX_SESSIONS; i++) {
1594 Session *s = &sessions[i];
1595 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1596 debug("session_by_tty: session %d tty %s", i, tty);
1600 debug("session_by_tty: unknown tty %.100s", tty);
1606 session_by_channel(int id)
1609 for (i = 0; i < MAX_SESSIONS; i++) {
1610 Session *s = &sessions[i];
1611 if (s->used && s->chanid == id) {
1612 debug("session_by_channel: session %d channel %d", i, id);
1616 debug("session_by_channel: unknown channel %d", id);
1622 session_by_pid(pid_t pid)
1625 debug("session_by_pid: pid %ld", (long)pid);
1626 for (i = 0; i < MAX_SESSIONS; i++) {
1627 Session *s = &sessions[i];
1628 if (s->used && s->pid == pid)
1631 error("session_by_pid: unknown pid %ld", (long)pid);
1637 session_window_change_req(Session *s)
1639 s->col = packet_get_int();
1640 s->row = packet_get_int();
1641 s->xpixel = packet_get_int();
1642 s->ypixel = packet_get_int();
1644 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1649 session_pty_req(Session *s)
1655 debug("Allocating a pty not permitted for this authentication.");
1658 if (s->ttyfd != -1) {
1659 packet_disconnect("Protocol error: you already have a pty.");
1662 /* Get the time and hostname when the user last logged in. */
1663 if (options.print_lastlog) {
1664 s->hostname[0] = '\0';
1665 s->last_login_time = get_last_login_time(s->pw->pw_uid,
1666 s->pw->pw_name, s->hostname, sizeof(s->hostname));
1669 s->term = packet_get_string(&len);
1672 s->col = packet_get_int();
1673 s->row = packet_get_int();
1675 s->row = packet_get_int();
1676 s->col = packet_get_int();
1678 s->xpixel = packet_get_int();
1679 s->ypixel = packet_get_int();
1681 if (strcmp(s->term, "") == 0) {
1686 /* Allocate a pty and open it. */
1687 debug("Allocating pty.");
1688 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1694 error("session_pty_req: session %d alloc failed", s->self);
1697 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1699 /* for SSH1 the tty modes length is not given */
1701 n_bytes = packet_remaining();
1702 tty_parse_modes(s->ttyfd, &n_bytes);
1705 * Add a cleanup function to clear the utmp entry and record logout
1706 * time in case we call fatal() (e.g., the connection gets closed).
1708 fatal_add_cleanup(session_pty_cleanup, (void *)s);
1710 pty_setowner(s->pw, s->tty);
1712 /* Set window size from the packet. */
1713 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1716 session_proctitle(s);
1721 session_subsystem_req(Session *s)
1726 char *cmd, *subsys = packet_get_string(&len);
1730 logit("subsystem request for %.100s", subsys);
1732 for (i = 0; i < options.num_subsystems; i++) {
1733 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1734 cmd = options.subsystem_command[i];
1735 if (stat(cmd, &st) < 0) {
1736 error("subsystem: cannot stat %s: %s", cmd,
1740 debug("subsystem: exec() %s", cmd);
1741 s->is_subsystem = 1;
1749 logit("subsystem request for %.100s failed, subsystem not found",
1757 session_x11_req(Session *s)
1761 s->single_connection = packet_get_char();
1762 s->auth_proto = packet_get_string(NULL);
1763 s->auth_data = packet_get_string(NULL);
1764 s->screen = packet_get_int();
1767 success = session_setup_x11fwd(s);
1769 xfree(s->auth_proto);
1770 xfree(s->auth_data);
1771 s->auth_proto = NULL;
1772 s->auth_data = NULL;
1778 session_shell_req(Session *s)
1786 session_exec_req(Session *s)
1789 char *command = packet_get_string(&len);
1791 do_exec(s, command);
1797 session_break_req(Session *s)
1801 break_length = packet_get_int(); /* ignored */
1804 if (s->ttyfd == -1 ||
1805 tcsendbreak(s->ttyfd, 0) < 0)
1811 session_auth_agent_req(Session *s)
1813 static int called = 0;
1815 if (no_agent_forwarding_flag) {
1816 debug("session_auth_agent_req: no_agent_forwarding_flag");
1823 return auth_input_request_forwarding(s->pw);
1828 session_input_channel_req(Channel *c, const char *rtype)
1833 if ((s = session_by_channel(c->self)) == NULL) {
1834 logit("session_input_channel_req: no session %d req %.100s",
1838 debug("session_input_channel_req: session %d req %s", s->self, rtype);
1841 * a session is in LARVAL state until a shell, a command
1842 * or a subsystem is executed
1844 if (c->type == SSH_CHANNEL_LARVAL) {
1845 if (strcmp(rtype, "shell") == 0) {
1846 success = session_shell_req(s);
1847 } else if (strcmp(rtype, "exec") == 0) {
1848 success = session_exec_req(s);
1849 } else if (strcmp(rtype, "pty-req") == 0) {
1850 success = session_pty_req(s);
1851 } else if (strcmp(rtype, "x11-req") == 0) {
1852 success = session_x11_req(s);
1853 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1854 success = session_auth_agent_req(s);
1855 } else if (strcmp(rtype, "subsystem") == 0) {
1856 success = session_subsystem_req(s);
1857 } else if (strcmp(rtype, "break") == 0) {
1858 success = session_break_req(s);
1861 if (strcmp(rtype, "window-change") == 0) {
1862 success = session_window_change_req(s);
1868 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1871 fatal("session_set_fds: called for proto != 2.0");
1873 * now that have a child and a pipe to the child,
1874 * we can activate our channel and register the fd's
1876 if (s->chanid == -1)
1877 fatal("no channel for session %d", s->self);
1878 channel_set_fds(s->chanid,
1880 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1882 CHAN_SES_WINDOW_DEFAULT);
1886 * Function to perform pty cleanup. Also called if we get aborted abnormally
1887 * (e.g., due to a dropped connection).
1890 session_pty_cleanup2(void *session)
1892 Session *s = session;
1895 error("session_pty_cleanup: no session");
1901 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1903 /* Record that the user has logged out. */
1905 record_logout(s->pid, s->tty, s->pw->pw_name);
1907 /* Release the pseudo-tty. */
1909 pty_release(s->tty);
1912 * Close the server side of the socket pairs. We must do this after
1913 * the pty cleanup, so that another process doesn't get this pty
1914 * while we're still cleaning up.
1916 if (close(s->ptymaster) < 0)
1917 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
1919 /* unlink pty from session */
1924 session_pty_cleanup(void *session)
1926 PRIVSEP(session_pty_cleanup2(session));
1932 #define SSH_SIG(x) if (sig == SIG ## x) return #x
1947 return "SIG@openssh.com";
1951 session_exit_message(Session *s, int status)
1955 if ((c = channel_lookup(s->chanid)) == NULL)
1956 fatal("session_exit_message: session %d: no channel %d",
1957 s->self, s->chanid);
1958 debug("session_exit_message: session %d channel %d pid %ld",
1959 s->self, s->chanid, (long)s->pid);
1961 if (WIFEXITED(status)) {
1962 channel_request_start(s->chanid, "exit-status", 0);
1963 packet_put_int(WEXITSTATUS(status));
1965 } else if (WIFSIGNALED(status)) {
1966 channel_request_start(s->chanid, "exit-signal", 0);
1967 packet_put_cstring(sig2name(WTERMSIG(status)));
1969 packet_put_char(WCOREDUMP(status));
1970 #else /* WCOREDUMP */
1972 #endif /* WCOREDUMP */
1973 packet_put_cstring("");
1974 packet_put_cstring("");
1977 /* Some weird exit cause. Just exit. */
1978 packet_disconnect("wait returned status %04x.", status);
1981 /* disconnect channel */
1982 debug("session_exit_message: release channel %d", s->chanid);
1983 channel_cancel_cleanup(s->chanid);
1985 * emulate a write failure with 'chan_write_failed', nobody will be
1986 * interested in data we write.
1987 * Note that we must not call 'chan_read_failed', since there could
1988 * be some more data waiting in the pipe.
1990 if (c->ostate != CHAN_OUTPUT_CLOSED)
1991 chan_write_failed(c);
1996 session_close(Session *s)
1998 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
1999 if (s->ttyfd != -1) {
2000 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2001 session_pty_cleanup(s);
2007 if (s->auth_display)
2008 xfree(s->auth_display);
2010 xfree(s->auth_data);
2012 xfree(s->auth_proto);
2014 session_proctitle(s);
2018 session_close_by_pid(pid_t pid, int status)
2020 Session *s = session_by_pid(pid);
2022 debug("session_close_by_pid: no session for pid %ld",
2026 if (s->chanid != -1)
2027 session_exit_message(s, status);
2032 * this is called when a channel dies before
2033 * the session 'child' itself dies
2036 session_close_by_channel(int id, void *arg)
2038 Session *s = session_by_channel(id);
2040 debug("session_close_by_channel: no session for id %d", id);
2043 debug("session_close_by_channel: channel %d child %ld",
2046 debug("session_close_by_channel: channel %d: has child", id);
2048 * delay detach of session, but release pty, since
2049 * the fd's to the child are already closed
2051 if (s->ttyfd != -1) {
2052 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2053 session_pty_cleanup(s);
2057 /* detach by removing callback */
2058 channel_cancel_cleanup(s->chanid);
2064 session_destroy_all(void (*closefunc)(Session *))
2067 for (i = 0; i < MAX_SESSIONS; i++) {
2068 Session *s = &sessions[i];
2070 if (closefunc != NULL)
2079 session_tty_list(void)
2081 static char buf[1024];
2086 for (i = 0; i < MAX_SESSIONS; i++) {
2087 Session *s = &sessions[i];
2088 if (s->used && s->ttyfd != -1) {
2090 if (strncmp(s->tty, "/dev/", 5) != 0) {
2091 cp = strrchr(s->tty, '/');
2092 cp = (cp == NULL) ? s->tty : cp + 1;
2097 strlcat(buf, ",", sizeof buf);
2098 strlcat(buf, cp, sizeof buf);
2102 strlcpy(buf, "notty", sizeof buf);
2107 session_proctitle(Session *s)
2110 error("no user for session %d", s->self);
2112 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2116 session_setup_x11fwd(Session *s)
2119 char display[512], auth_display[512];
2120 char hostname[MAXHOSTNAMELEN];
2122 if (no_x11_forwarding_flag) {
2123 packet_send_debug("X11 forwarding disabled in user configuration file.");
2126 if (!options.x11_forwarding) {
2127 debug("X11 forwarding disabled in server configuration file.");
2130 if (!options.xauth_location ||
2131 (stat(options.xauth_location, &st) == -1)) {
2132 packet_send_debug("No xauth program; cannot forward with spoofing.");
2135 if (options.use_login) {
2136 packet_send_debug("X11 forwarding disabled; "
2137 "not compatible with UseLogin=yes.");
2140 if (s->display != NULL) {
2141 debug("X11 display already set.");
2144 if (x11_create_display_inet(options.x11_display_offset,
2145 options.x11_use_localhost, s->single_connection,
2146 &s->display_number) == -1) {
2147 debug("x11_create_display_inet failed.");
2151 /* Set up a suitable value for the DISPLAY variable. */
2152 if (gethostname(hostname, sizeof(hostname)) < 0)
2153 fatal("gethostname: %.100s", strerror(errno));
2155 * auth_display must be used as the displayname when the
2156 * authorization entry is added with xauth(1). This will be
2157 * different than the DISPLAY string for localhost displays.
2159 if (options.x11_use_localhost) {
2160 snprintf(display, sizeof display, "localhost:%u.%u",
2161 s->display_number, s->screen);
2162 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2163 s->display_number, s->screen);
2164 s->display = xstrdup(display);
2165 s->auth_display = xstrdup(auth_display);
2167 #ifdef IPADDR_IN_DISPLAY
2169 struct in_addr my_addr;
2171 he = gethostbyname(hostname);
2173 error("Can't get IP address for X11 DISPLAY.");
2174 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2177 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2178 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2179 s->display_number, s->screen);
2181 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2182 s->display_number, s->screen);
2184 s->display = xstrdup(display);
2185 s->auth_display = xstrdup(display);
2192 do_authenticated2(Authctxt *authctxt)
2194 server_loop2(authctxt);
2196 if (options.gss_cleanup_creds)
2197 ssh_gssapi_cleanup_creds(NULL);