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 $");
51 #include "auth-options.h"
52 #include "pathnames.h"
56 #include "serverloop.h"
59 #include "monitor_wrap.h"
67 Session *session_new(void);
68 void session_set_fds(Session *, int, int, int);
69 void session_pty_cleanup(void *);
70 void session_proctitle(Session *);
71 int session_setup_x11fwd(Session *);
72 void do_exec_pty(Session *, const char *);
73 void do_exec_no_pty(Session *, const char *);
74 void do_exec(Session *, const char *);
75 void do_login(Session *, const char *);
76 #ifdef LOGIN_NEEDS_UTMPX
77 static void do_pre_login(Session *s);
79 void do_child(Session *, const char *);
81 int check_quietlogin(Session *, const char *);
83 static void do_authenticated1(Authctxt *);
84 static void do_authenticated2(Authctxt *);
86 static int session_pty_req(Session *);
89 extern ServerOptions options;
90 extern char *__progname;
91 extern int log_stderr;
92 extern int debug_flag;
93 extern u_int utmp_len;
94 extern int startup_pipe;
95 extern void destroy_sensitive_data(void);
96 extern Buffer loginmsg;
98 /* original command from peer. */
99 const char *original_command = NULL;
102 #define MAX_SESSIONS 10
103 Session sessions[MAX_SESSIONS];
105 #ifdef HAVE_LOGIN_CAP
109 /* Name and directory of socket for authentication agent forwarding. */
110 static char *auth_sock_name = NULL;
111 static char *auth_sock_dir = NULL;
113 /* removes the agent forwarding socket */
116 auth_sock_cleanup_proc(void *_pw)
118 struct passwd *pw = _pw;
120 if (auth_sock_name != NULL) {
121 temporarily_use_uid(pw);
122 unlink(auth_sock_name);
123 rmdir(auth_sock_dir);
124 auth_sock_name = NULL;
130 auth_input_request_forwarding(struct passwd * pw)
134 struct sockaddr_un sunaddr;
136 if (auth_sock_name != NULL) {
137 error("authentication forwarding requested twice.");
141 /* Temporarily drop privileged uid for mkdir/bind. */
142 temporarily_use_uid(pw);
144 /* Allocate a buffer for the socket name, and format the name. */
145 auth_sock_name = xmalloc(MAXPATHLEN);
146 auth_sock_dir = xmalloc(MAXPATHLEN);
147 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
149 /* Create private directory for socket */
150 if (mkdtemp(auth_sock_dir) == NULL) {
151 packet_send_debug("Agent forwarding disabled: "
152 "mkdtemp() failed: %.100s", strerror(errno));
154 xfree(auth_sock_name);
155 xfree(auth_sock_dir);
156 auth_sock_name = NULL;
157 auth_sock_dir = NULL;
160 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
161 auth_sock_dir, (long) getpid());
163 /* delete agent socket on fatal() */
164 fatal_add_cleanup(auth_sock_cleanup_proc, pw);
166 /* Create the socket. */
167 sock = socket(AF_UNIX, SOCK_STREAM, 0);
169 packet_disconnect("socket: %.100s", strerror(errno));
171 /* Bind it to the name. */
172 memset(&sunaddr, 0, sizeof(sunaddr));
173 sunaddr.sun_family = AF_UNIX;
174 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
176 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
177 packet_disconnect("bind: %.100s", strerror(errno));
179 /* Restore the privileged uid. */
182 /* Start listening on the socket. */
183 if (listen(sock, 5) < 0)
184 packet_disconnect("listen: %.100s", strerror(errno));
186 /* Allocate a channel for the authentication agent socket. */
187 nc = channel_new("auth socket",
188 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
189 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
190 0, "auth socket", 1);
191 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
197 do_authenticated(Authctxt *authctxt)
199 setproctitle("%s", authctxt->pw->pw_name);
202 * Cancel the alarm we set to limit the time taken for
206 if (startup_pipe != -1) {
211 /* setup the channel layer */
212 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
213 channel_permit_all_opens();
216 do_authenticated2(authctxt);
218 do_authenticated1(authctxt);
220 /* remove agent socket */
221 if (auth_sock_name != NULL)
222 auth_sock_cleanup_proc(authctxt->pw);
224 if (options.kerberos_ticket_cleanup)
225 krb5_cleanup_proc(authctxt);
230 * Prepares for an interactive session. This is called after the user has
231 * been successfully authenticated. During this message exchange, pseudo
232 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
233 * are requested, etc.
236 do_authenticated1(Authctxt *authctxt)
240 int success, type, screen_flag;
241 int enable_compression_after_reply = 0;
242 u_int proto_len, data_len, dlen, compression_level = 0;
245 s->authctxt = authctxt;
246 s->pw = authctxt->pw;
249 * We stay in this loop until the client requests to execute a shell
255 /* Get a packet from the client. */
256 type = packet_read();
258 /* Process the packet. */
260 case SSH_CMSG_REQUEST_COMPRESSION:
261 compression_level = packet_get_int();
263 if (compression_level < 1 || compression_level > 9) {
264 packet_send_debug("Received illegal compression level %d.",
268 if (!options.compression) {
269 debug2("compression disabled");
272 /* Enable compression after we have responded with SUCCESS. */
273 enable_compression_after_reply = 1;
277 case SSH_CMSG_REQUEST_PTY:
278 success = session_pty_req(s);
281 case SSH_CMSG_X11_REQUEST_FORWARDING:
282 s->auth_proto = packet_get_string(&proto_len);
283 s->auth_data = packet_get_string(&data_len);
285 screen_flag = packet_get_protocol_flags() &
286 SSH_PROTOFLAG_SCREEN_NUMBER;
287 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
289 if (packet_remaining() == 4) {
291 debug2("Buggy client: "
292 "X11 screen flag missing");
293 s->screen = packet_get_int();
298 success = session_setup_x11fwd(s);
300 xfree(s->auth_proto);
302 s->auth_proto = NULL;
307 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
308 if (no_agent_forwarding_flag || compat13) {
309 debug("Authentication agent forwarding not permitted for this authentication.");
312 debug("Received authentication agent forwarding request.");
313 success = auth_input_request_forwarding(s->pw);
316 case SSH_CMSG_PORT_FORWARD_REQUEST:
317 if (no_port_forwarding_flag) {
318 debug("Port forwarding not permitted for this authentication.");
321 if (!options.allow_tcp_forwarding) {
322 debug("Port forwarding not permitted.");
325 debug("Received TCP/IP port forwarding request.");
326 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
330 case SSH_CMSG_MAX_PACKET_SIZE:
331 if (packet_set_maxsize(packet_get_int()) > 0)
335 case SSH_CMSG_EXEC_SHELL:
336 case SSH_CMSG_EXEC_CMD:
337 if (type == SSH_CMSG_EXEC_CMD) {
338 command = packet_get_string(&dlen);
339 debug("Exec command '%.500s'", command);
351 * Any unknown messages in this phase are ignored,
352 * and a failure message is returned.
354 logit("Unknown packet type received after authentication: %d", type);
356 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
360 /* Enable compression now that we have replied if appropriate. */
361 if (enable_compression_after_reply) {
362 enable_compression_after_reply = 0;
363 packet_start_compression(compression_level);
369 * This is called to fork and execute a command when we have no tty. This
370 * will call do_child from the child, and server_loop from the parent after
371 * setting up file descriptors and such.
374 do_exec_no_pty(Session *s, const char *command)
379 int pin[2], pout[2], perr[2];
380 /* Allocate pipes for communicating with the program. */
381 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
382 packet_disconnect("Could not create pipes: %.100s",
384 #else /* USE_PIPES */
385 int inout[2], err[2];
386 /* Uses socket pairs to communicate with the program. */
387 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
388 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
389 packet_disconnect("Could not create socket pairs: %.100s",
391 #endif /* USE_PIPES */
393 fatal("do_exec_no_pty: no session");
395 session_proctitle(s);
398 if (options.use_pam) {
400 if (is_pam_password_change_required())
401 packet_disconnect("Password change required but no "
406 /* Fork the child. */
407 if ((pid = fork()) == 0) {
408 fatal_remove_all_cleanups();
410 /* Child. Reinitialize the log since the pid has changed. */
411 log_init(__progname, options.log_level, options.log_facility, log_stderr);
414 * Create a new session and process group since the 4.4BSD
415 * setlogin() affects the entire process group.
418 error("setsid failed: %.100s", strerror(errno));
422 * Redirect stdin. We close the parent side of the socket
423 * pair, and make the child side the standard input.
426 if (dup2(pin[0], 0) < 0)
427 perror("dup2 stdin");
430 /* Redirect stdout. */
432 if (dup2(pout[1], 1) < 0)
433 perror("dup2 stdout");
436 /* Redirect stderr. */
438 if (dup2(perr[1], 2) < 0)
439 perror("dup2 stderr");
441 #else /* USE_PIPES */
443 * Redirect stdin, stdout, and stderr. Stdin and stdout will
444 * use the same socket, as some programs (particularly rdist)
445 * seem to depend on it.
449 if (dup2(inout[0], 0) < 0) /* stdin */
450 perror("dup2 stdin");
451 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
452 perror("dup2 stdout");
453 if (dup2(err[0], 2) < 0) /* stderr */
454 perror("dup2 stderr");
455 #endif /* USE_PIPES */
458 cray_init_job(s->pw); /* set up cray jid and tmpdir */
461 /* Do processing for the child (exec command etc). */
462 do_child(s, command);
466 signal(WJSIGNAL, cray_job_termination_handler);
470 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
473 packet_disconnect("fork failed: %.100s", strerror(errno));
475 /* Set interactive/non-interactive mode. */
476 packet_set_interactive(s->display != NULL);
478 /* We are the parent. Close the child sides of the pipes. */
484 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
486 /* Enter the interactive session. */
487 server_loop(pid, pin[1], pout[0], perr[0]);
488 /* server_loop has closed pin[1], pout[0], and perr[0]. */
490 #else /* USE_PIPES */
491 /* We are the parent. Close the child sides of the socket pairs. */
496 * Enter the interactive session. Note: server_loop must be able to
497 * handle the case that fdin and fdout are the same.
500 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
502 server_loop(pid, inout[1], inout[1], err[1]);
503 /* server_loop has closed inout[1] and err[1]. */
505 #endif /* USE_PIPES */
509 * This is called to fork and execute a command when we have a tty. This
510 * will call do_child from the child, and server_loop from the parent after
511 * setting up file descriptors, controlling tty, updating wtmp, utmp,
512 * lastlog, and other such operations.
515 do_exec_pty(Session *s, const char *command)
517 int fdout, ptyfd, ttyfd, ptymaster;
521 fatal("do_exec_pty: no session");
526 if (options.use_pam) {
527 do_pam_set_tty(s->tty);
532 /* Fork the child. */
533 if ((pid = fork()) == 0) {
534 fatal_remove_all_cleanups();
536 /* Child. Reinitialize the log because the pid has changed. */
537 log_init(__progname, options.log_level, options.log_facility, log_stderr);
538 /* Close the master side of the pseudo tty. */
541 /* Make the pseudo tty our controlling tty. */
542 pty_make_controlling_tty(&ttyfd, s->tty);
544 /* Redirect stdin/stdout/stderr from the pseudo tty. */
545 if (dup2(ttyfd, 0) < 0)
546 error("dup2 stdin: %s", strerror(errno));
547 if (dup2(ttyfd, 1) < 0)
548 error("dup2 stdout: %s", strerror(errno));
549 if (dup2(ttyfd, 2) < 0)
550 error("dup2 stderr: %s", strerror(errno));
552 /* Close the extra descriptor for the pseudo tty. */
555 /* record login, etc. similar to login(1) */
557 if (!(options.use_login && command == NULL)) {
559 cray_init_job(s->pw); /* set up cray jid and tmpdir */
561 do_login(s, command);
563 # ifdef LOGIN_NEEDS_UTMPX
569 /* Do common processing for the child, such as execing the command. */
570 do_child(s, command);
574 signal(WJSIGNAL, cray_job_termination_handler);
578 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
581 packet_disconnect("fork failed: %.100s", strerror(errno));
584 /* Parent. Close the slave side of the pseudo tty. */
588 * Create another descriptor of the pty master side for use as the
589 * standard input. We could use the original descriptor, but this
590 * simplifies code in server_loop. The descriptor is bidirectional.
594 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
596 /* we keep a reference to the pty master */
597 ptymaster = dup(ptyfd);
599 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
600 s->ptymaster = ptymaster;
602 /* Enter interactive session. */
603 packet_set_interactive(1);
605 session_set_fds(s, ptyfd, fdout, -1);
607 server_loop(pid, ptyfd, fdout, -1);
608 /* server_loop _has_ closed ptyfd and fdout. */
612 #ifdef LOGIN_NEEDS_UTMPX
614 do_pre_login(Session *s)
617 struct sockaddr_storage from;
618 pid_t pid = getpid();
621 * Get IP address of client. If the connection is not a socket, let
622 * the address be 0.0.0.0.
624 memset(&from, 0, sizeof(from));
625 fromlen = sizeof(from);
626 if (packet_connection_is_on_socket()) {
627 if (getpeername(packet_get_connection_in(),
628 (struct sockaddr *) & from, &fromlen) < 0) {
629 debug("getpeername: %.100s", strerror(errno));
634 record_utmp_only(pid, s->tty, s->pw->pw_name,
635 get_remote_name_or_ip(utmp_len, options.use_dns),
636 (struct sockaddr *)&from, fromlen);
641 * This is called to fork and execute a command. If another command is
642 * to be forced, execute that instead.
645 do_exec(Session *s, const char *command)
647 if (forced_command) {
648 original_command = command;
649 command = forced_command;
650 debug("Forced command '%.900s'", command);
654 if (options.gss_authentication) {
655 temporarily_use_uid(s->pw);
656 ssh_gssapi_storecreds();
662 do_exec_pty(s, command);
664 do_exec_no_pty(s, command);
666 original_command = NULL;
670 /* administrative, login(1)-like work */
672 do_login(Session *s, const char *command)
676 struct sockaddr_storage from;
677 struct passwd * pw = s->pw;
678 pid_t pid = getpid();
681 * Get IP address of client. If the connection is not a socket, let
682 * the address be 0.0.0.0.
684 memset(&from, 0, sizeof(from));
685 fromlen = sizeof(from);
686 if (packet_connection_is_on_socket()) {
687 if (getpeername(packet_get_connection_in(),
688 (struct sockaddr *) & from, &fromlen) < 0) {
689 debug("getpeername: %.100s", strerror(errno));
694 /* Record that there was a login on that tty from the remote host. */
696 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
697 get_remote_name_or_ip(utmp_len,
699 (struct sockaddr *)&from, fromlen);
703 * If password change is needed, do it now.
704 * This needs to occur before the ~/.hushlogin check.
706 if (options.use_pam && is_pam_password_change_required()) {
707 print_pam_messages();
709 /* XXX - signal [net] parent to enable forwardings */
713 if (check_quietlogin(s, command))
717 if (options.use_pam && !is_pam_password_change_required())
718 print_pam_messages();
721 /* display post-login message */
722 if (buffer_len(&loginmsg) > 0) {
723 buffer_append(&loginmsg, "\0", 1);
724 printf("%s\n", (char *)buffer_ptr(&loginmsg));
726 buffer_free(&loginmsg);
728 #ifndef NO_SSH_LASTLOG
729 if (options.print_lastlog && s->last_login_time != 0) {
730 time_string = ctime(&s->last_login_time);
731 if (strchr(time_string, '\n'))
732 *strchr(time_string, '\n') = 0;
733 if (strcmp(s->hostname, "") == 0)
734 printf("Last login: %s\r\n", time_string);
736 printf("Last login: %s from %s\r\n", time_string,
739 #endif /* NO_SSH_LASTLOG */
745 * Display the message of the day.
753 if (options.print_motd) {
754 #ifdef HAVE_LOGIN_CAP
755 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
758 f = fopen("/etc/motd", "r");
761 while (fgets(buf, sizeof(buf), f))
770 * Check for quiet login, either .hushlogin or command given.
773 check_quietlogin(Session *s, const char *command)
776 struct passwd *pw = s->pw;
779 /* Return 1 if .hushlogin exists or a command given. */
782 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
783 #ifdef HAVE_LOGIN_CAP
784 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
787 if (stat(buf, &st) >= 0)
794 * Sets the value of the given variable in the environment. If the variable
795 * already exists, its value is overriden.
798 child_set_env(char ***envp, u_int *envsizep, const char *name,
806 * If we're passed an uninitialized list, allocate a single null
807 * entry before continuing.
809 if (*envp == NULL && *envsizep == 0) {
810 *envp = xmalloc(sizeof(char *));
816 * Find the slot where the value should be stored. If the variable
817 * already exists, we reuse the slot; otherwise we append a new slot
818 * at the end of the array, expanding if necessary.
821 namelen = strlen(name);
822 for (i = 0; env[i]; i++)
823 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
826 /* Reuse the slot. */
829 /* New variable. Expand if necessary. */
831 if (i >= envsize - 1) {
833 fatal("child_set_env: too many env vars");
835 env = (*envp) = xrealloc(env, envsize * sizeof(char *));
838 /* Need to set the NULL pointer at end of array beyond the new slot. */
842 /* Allocate space and format the variable in the appropriate slot. */
843 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
844 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
848 * Reads environment variables from the given file and adds/overrides them
849 * into the environment. If the file does not exist, this does nothing.
850 * Otherwise, it must consist of empty lines, comments (line starts with '#')
851 * and assignments of the form name=value. No other forms are allowed.
854 read_environment_file(char ***env, u_int *envsize,
855 const char *filename)
862 f = fopen(filename, "r");
866 while (fgets(buf, sizeof(buf), f)) {
868 fatal("Too many lines in environment file %s", filename);
869 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
871 if (!*cp || *cp == '#' || *cp == '\n')
873 if (strchr(cp, '\n'))
874 *strchr(cp, '\n') = '\0';
875 value = strchr(cp, '=');
877 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
882 * Replace the equals sign by nul, and advance value to
887 child_set_env(env, envsize, cp, value);
892 #ifdef HAVE_ETC_DEFAULT_LOGIN
894 * Return named variable from specified environment, or NULL if not present.
897 child_get_env(char **env, const char *name)
903 for (i=0; env[i] != NULL; i++)
904 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
905 return(env[i] + len + 1);
910 * Read /etc/default/login.
911 * We pick up the PATH (or SUPATH for root) and UMASK.
914 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
916 char **tmpenv = NULL, *var;
917 u_int i, tmpenvsize = 0;
921 * We don't want to copy the whole file to the child's environment,
922 * so we use a temporary environment and copy the variables we're
925 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
931 var = child_get_env(tmpenv, "SUPATH");
933 var = child_get_env(tmpenv, "PATH");
935 child_set_env(env, envsize, "PATH", var);
937 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
938 if (sscanf(var, "%5lo", &mask) == 1)
941 for (i = 0; tmpenv[i] != NULL; i++)
945 #endif /* HAVE_ETC_DEFAULT_LOGIN */
947 void copy_environment(char **source, char ***env, u_int *envsize)
949 char *var_name, *var_val;
955 for(i = 0; source[i] != NULL; i++) {
956 var_name = xstrdup(source[i]);
957 if ((var_val = strstr(var_name, "=")) == NULL) {
963 debug3("Copy environment: %s=%s", var_name, var_val);
964 child_set_env(env, envsize, var_name, var_val);
971 do_setup_env(Session *s, const char *shell)
975 char **env, *laddr, *path = NULL;
976 struct passwd *pw = s->pw;
978 /* Initialize the environment. */
980 env = xmalloc(envsize * sizeof(char *));
985 * The Windows environment contains some setting which are
986 * important for a running system. They must not be dropped.
988 copy_environment(environ, &env, &envsize);
992 /* Allow any GSSAPI methods that we've used to alter
993 * the childs environment as they see fit
995 ssh_gssapi_do_child(&env, &envsize);
998 if (!options.use_login) {
999 /* Set basic environment. */
1000 child_set_env(&env, &envsize, "USER", pw->pw_name);
1001 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1003 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1005 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1006 #ifdef HAVE_LOGIN_CAP
1007 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1008 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1010 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1011 #else /* HAVE_LOGIN_CAP */
1012 # ifndef HAVE_CYGWIN
1014 * There's no standard path on Windows. The path contains
1015 * important components pointing to the system directories,
1016 * needed for loading shared libraries. So the path better
1017 * remains intact here.
1019 # ifdef HAVE_ETC_DEFAULT_LOGIN
1020 read_etc_default_login(&env, &envsize, pw->pw_uid);
1021 path = child_get_env(env, "PATH");
1022 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1023 if (path == NULL || *path == '\0') {
1024 child_set_env(&env, &envsize, "PATH",
1025 s->pw->pw_uid == 0 ?
1026 SUPERUSER_PATH : _PATH_STDPATH);
1028 # endif /* HAVE_CYGWIN */
1029 #endif /* HAVE_LOGIN_CAP */
1031 snprintf(buf, sizeof buf, "%.200s/%.50s",
1032 _PATH_MAILDIR, pw->pw_name);
1033 child_set_env(&env, &envsize, "MAIL", buf);
1035 /* Normal systems set SHELL by default. */
1036 child_set_env(&env, &envsize, "SHELL", shell);
1039 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1041 /* Set custom environment options from RSA authentication. */
1042 if (!options.use_login) {
1043 while (custom_environment) {
1044 struct envstring *ce = custom_environment;
1047 for (i = 0; str[i] != '=' && str[i]; i++)
1049 if (str[i] == '=') {
1051 child_set_env(&env, &envsize, str, str + i + 1);
1053 custom_environment = ce->next;
1059 /* SSH_CLIENT deprecated */
1060 snprintf(buf, sizeof buf, "%.50s %d %d",
1061 get_remote_ipaddr(), get_remote_port(), get_local_port());
1062 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1064 laddr = get_local_ipaddr(packet_get_connection_in());
1065 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1066 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1068 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1071 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1073 child_set_env(&env, &envsize, "TERM", s->term);
1075 child_set_env(&env, &envsize, "DISPLAY", s->display);
1076 if (original_command)
1077 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1081 if (cray_tmpdir[0] != '\0')
1082 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1083 #endif /* _UNICOS */
1089 if ((cp = getenv("AUTHSTATE")) != NULL)
1090 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1091 if ((cp = getenv("KRB5CCNAME")) != NULL)
1092 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1093 read_environment_file(&env, &envsize, "/etc/environment");
1097 if (s->authctxt->krb5_ticket_file)
1098 child_set_env(&env, &envsize, "KRB5CCNAME",
1099 s->authctxt->krb5_ticket_file);
1103 * Pull in any environment variables that may have
1106 if (options.use_pam) {
1107 char **p = fetch_pam_environment();
1109 copy_environment(p, &env, &envsize);
1110 free_pam_environment(p);
1112 #endif /* USE_PAM */
1114 if (auth_sock_name != NULL)
1115 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1118 /* read $HOME/.ssh/environment. */
1119 if (options.permit_user_env && !options.use_login) {
1120 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1121 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1122 read_environment_file(&env, &envsize, buf);
1125 /* dump the environment */
1126 fprintf(stderr, "Environment:\n");
1127 for (i = 0; env[i]; i++)
1128 fprintf(stderr, " %.200s\n", env[i]);
1134 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1135 * first in this order).
1138 do_rc_files(Session *s, const char *shell)
1146 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1148 /* ignore _PATH_SSH_USER_RC for subsystems */
1149 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1150 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1151 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1153 fprintf(stderr, "Running %s\n", cmd);
1154 f = popen(cmd, "w");
1157 fprintf(f, "%s %s\n", s->auth_proto,
1161 fprintf(stderr, "Could not run %s\n",
1163 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1165 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1166 _PATH_SSH_SYSTEM_RC);
1167 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1170 fprintf(f, "%s %s\n", s->auth_proto,
1174 fprintf(stderr, "Could not run %s\n",
1175 _PATH_SSH_SYSTEM_RC);
1176 } else if (do_xauth && options.xauth_location != NULL) {
1177 /* Add authority data to .Xauthority if appropriate. */
1180 "Running %.500s remove %.100s\n",
1181 options.xauth_location, s->auth_display);
1183 "%.500s add %.100s %.100s %.100s\n",
1184 options.xauth_location, s->auth_display,
1185 s->auth_proto, s->auth_data);
1187 snprintf(cmd, sizeof cmd, "%s -q -",
1188 options.xauth_location);
1189 f = popen(cmd, "w");
1191 fprintf(f, "remove %s\n",
1193 fprintf(f, "add %s %s %s\n",
1194 s->auth_display, s->auth_proto,
1198 fprintf(stderr, "Could not run %s\n",
1205 do_nologin(struct passwd *pw)
1210 #ifdef HAVE_LOGIN_CAP
1211 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1212 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1213 _PATH_NOLOGIN), "r");
1216 f = fopen(_PATH_NOLOGIN, "r");
1219 /* /etc/nologin exists. Print its contents and exit. */
1220 logit("User %.100s not allowed because %s exists",
1221 pw->pw_name, _PATH_NOLOGIN);
1222 while (fgets(buf, sizeof(buf), f))
1230 /* Set login name, uid, gid, and groups. */
1232 do_setusercontext(struct passwd *pw)
1235 if (getuid() == 0 || geteuid() == 0)
1236 #endif /* HAVE_CYGWIN */
1239 #ifdef HAVE_SETPCRED
1240 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1241 fatal("Failed to set process credentials");
1242 #endif /* HAVE_SETPCRED */
1243 #ifdef HAVE_LOGIN_CAP
1247 if (setusercontext(lc, pw, pw->pw_uid,
1248 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1249 perror("unable to set user context");
1253 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1254 /* Sets login uid for accounting */
1255 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1256 error("setluid: %s", strerror(errno));
1257 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1259 if (setlogin(pw->pw_name) < 0)
1260 error("setlogin failed: %s", strerror(errno));
1261 if (setgid(pw->pw_gid) < 0) {
1265 /* Initialize the group list. */
1266 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1267 perror("initgroups");
1273 * PAM credentials may take the form of supplementary groups.
1274 * These will have been wiped by the above initgroups() call.
1275 * Reestablish them here.
1277 if (options.use_pam) {
1281 # endif /* USE_PAM */
1282 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1283 irix_setusercontext(pw);
1284 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1288 /* Permanently switch to the desired uid. */
1289 permanently_set_uid(pw);
1296 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1297 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1301 launch_login(struct passwd *pw, const char *hostname)
1303 /* Launch login(1). */
1305 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1306 #ifdef xxxLOGIN_NEEDS_TERM
1307 (s->term ? s->term : "unknown"),
1308 #endif /* LOGIN_NEEDS_TERM */
1309 #ifdef LOGIN_NO_ENDOPT
1310 "-p", "-f", pw->pw_name, (char *)NULL);
1312 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1315 /* Login couldn't be executed, die. */
1322 * Performs common processing for the child, such as setting up the
1323 * environment, closing extra file descriptors, setting the user and group
1324 * ids, and executing the command or shell.
1327 do_child(Session *s, const char *command)
1329 extern char **environ;
1332 const char *shell, *shell0, *hostname = NULL;
1333 struct passwd *pw = s->pw;
1336 /* remove hostkey from the child's memory */
1337 destroy_sensitive_data();
1339 /* login(1) is only called if we execute the login shell */
1340 if (options.use_login && command != NULL)
1341 options.use_login = 0;
1344 cray_setup(pw->pw_uid, pw->pw_name, command);
1345 #endif /* _UNICOS */
1348 * Login(1) does this as well, and it needs uid 0 for the "-h"
1349 * switch, so we let login(1) to this for us.
1351 if (!options.use_login) {
1353 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1354 if (!check_quietlogin(s, command))
1356 #else /* HAVE_OSF_SIA */
1358 do_setusercontext(pw);
1359 #endif /* HAVE_OSF_SIA */
1363 * Get the shell from the password data. An empty shell field is
1364 * legal, and means /bin/sh.
1366 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1369 * Make sure $SHELL points to the shell from the password file,
1370 * even if shell is overridden from login.conf
1372 env = do_setup_env(s, shell);
1374 #ifdef HAVE_LOGIN_CAP
1375 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1378 /* we have to stash the hostname before we close our socket. */
1379 if (options.use_login)
1380 hostname = get_remote_name_or_ip(utmp_len,
1383 * Close the connection descriptors; note that this is the child, and
1384 * the server will still have the socket open, and it is important
1385 * that we do not shutdown it. Note that the descriptors cannot be
1386 * closed before building the environment, as we call
1387 * get_remote_ipaddr there.
1389 if (packet_get_connection_in() == packet_get_connection_out())
1390 close(packet_get_connection_in());
1392 close(packet_get_connection_in());
1393 close(packet_get_connection_out());
1396 * Close all descriptors related to channels. They will still remain
1397 * open in the parent.
1399 /* XXX better use close-on-exec? -markus */
1400 channel_close_all();
1403 * Close any extra file descriptors. Note that there may still be
1404 * descriptors left by system functions. They will be closed later.
1409 * Close any extra open file descriptors so that we don\'t have them
1410 * hanging around in clients. Note that we want to do this after
1411 * initgroups, because at least on Solaris 2.3 it leaves file
1414 for (i = 3; i < 64; i++)
1418 * Must take new environment into use so that .ssh/rc,
1419 * /etc/ssh/sshrc and xauth are run in the proper environment.
1423 /* Change current directory to the user\'s home directory. */
1424 if (chdir(pw->pw_dir) < 0) {
1425 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1426 pw->pw_dir, strerror(errno));
1427 #ifdef HAVE_LOGIN_CAP
1428 if (login_getcapbool(lc, "requirehome", 0))
1433 if (!options.use_login)
1434 do_rc_files(s, shell);
1436 /* restore SIGPIPE for child */
1437 signal(SIGPIPE, SIG_DFL);
1439 if (options.use_login) {
1440 launch_login(pw, hostname);
1444 /* Get the last component of the shell name. */
1445 if ((shell0 = strrchr(shell, '/')) != NULL)
1451 * If we have no command, execute the shell. In this case, the shell
1452 * name to be passed in argv[0] is preceded by '-' to indicate that
1453 * this is a login shell.
1458 /* Start the shell. Set initial character to '-'. */
1461 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1462 >= sizeof(argv0) - 1) {
1468 /* Execute the shell. */
1471 execve(shell, argv, env);
1473 /* Executing the shell failed. */
1478 * Execute the command using the user's shell. This uses the -c
1479 * option to execute the command.
1481 argv[0] = (char *) shell0;
1483 argv[2] = (char *) command;
1485 execve(shell, argv, env);
1494 static int did_init = 0;
1496 debug("session_new: init");
1497 for (i = 0; i < MAX_SESSIONS; i++) {
1498 sessions[i].used = 0;
1502 for (i = 0; i < MAX_SESSIONS; i++) {
1503 Session *s = &sessions[i];
1505 memset(s, 0, sizeof(*s));
1511 debug("session_new: session %d", i);
1522 for (i = 0; i < MAX_SESSIONS; i++) {
1523 Session *s = &sessions[i];
1524 debug("dump: used %d session %d %p channel %d pid %ld",
1534 session_open(Authctxt *authctxt, int chanid)
1536 Session *s = session_new();
1537 debug("session_open: channel %d", chanid);
1539 error("no more sessions");
1542 s->authctxt = authctxt;
1543 s->pw = authctxt->pw;
1545 fatal("no user for session %d", s->self);
1546 debug("session_open: session %d: link with channel %d", s->self, chanid);
1552 session_by_tty(char *tty)
1555 for (i = 0; i < MAX_SESSIONS; i++) {
1556 Session *s = &sessions[i];
1557 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1558 debug("session_by_tty: session %d tty %s", i, tty);
1562 debug("session_by_tty: unknown tty %.100s", tty);
1568 session_by_channel(int id)
1571 for (i = 0; i < MAX_SESSIONS; i++) {
1572 Session *s = &sessions[i];
1573 if (s->used && s->chanid == id) {
1574 debug("session_by_channel: session %d channel %d", i, id);
1578 debug("session_by_channel: unknown channel %d", id);
1584 session_by_pid(pid_t pid)
1587 debug("session_by_pid: pid %ld", (long)pid);
1588 for (i = 0; i < MAX_SESSIONS; i++) {
1589 Session *s = &sessions[i];
1590 if (s->used && s->pid == pid)
1593 error("session_by_pid: unknown pid %ld", (long)pid);
1599 session_window_change_req(Session *s)
1601 s->col = packet_get_int();
1602 s->row = packet_get_int();
1603 s->xpixel = packet_get_int();
1604 s->ypixel = packet_get_int();
1606 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1611 session_pty_req(Session *s)
1617 debug("Allocating a pty not permitted for this authentication.");
1620 if (s->ttyfd != -1) {
1621 packet_disconnect("Protocol error: you already have a pty.");
1624 /* Get the time and hostname when the user last logged in. */
1625 if (options.print_lastlog) {
1626 s->hostname[0] = '\0';
1627 s->last_login_time = get_last_login_time(s->pw->pw_uid,
1628 s->pw->pw_name, s->hostname, sizeof(s->hostname));
1631 s->term = packet_get_string(&len);
1634 s->col = packet_get_int();
1635 s->row = packet_get_int();
1637 s->row = packet_get_int();
1638 s->col = packet_get_int();
1640 s->xpixel = packet_get_int();
1641 s->ypixel = packet_get_int();
1643 if (strcmp(s->term, "") == 0) {
1648 /* Allocate a pty and open it. */
1649 debug("Allocating pty.");
1650 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1656 error("session_pty_req: session %d alloc failed", s->self);
1659 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1661 /* for SSH1 the tty modes length is not given */
1663 n_bytes = packet_remaining();
1664 tty_parse_modes(s->ttyfd, &n_bytes);
1667 * Add a cleanup function to clear the utmp entry and record logout
1668 * time in case we call fatal() (e.g., the connection gets closed).
1670 fatal_add_cleanup(session_pty_cleanup, (void *)s);
1672 pty_setowner(s->pw, s->tty);
1674 /* Set window size from the packet. */
1675 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1678 session_proctitle(s);
1683 session_subsystem_req(Session *s)
1688 char *cmd, *subsys = packet_get_string(&len);
1692 logit("subsystem request for %.100s", subsys);
1694 for (i = 0; i < options.num_subsystems; i++) {
1695 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1696 cmd = options.subsystem_command[i];
1697 if (stat(cmd, &st) < 0) {
1698 error("subsystem: cannot stat %s: %s", cmd,
1702 debug("subsystem: exec() %s", cmd);
1703 s->is_subsystem = 1;
1711 logit("subsystem request for %.100s failed, subsystem not found",
1719 session_x11_req(Session *s)
1723 s->single_connection = packet_get_char();
1724 s->auth_proto = packet_get_string(NULL);
1725 s->auth_data = packet_get_string(NULL);
1726 s->screen = packet_get_int();
1729 success = session_setup_x11fwd(s);
1731 xfree(s->auth_proto);
1732 xfree(s->auth_data);
1733 s->auth_proto = NULL;
1734 s->auth_data = NULL;
1740 session_shell_req(Session *s)
1748 session_exec_req(Session *s)
1751 char *command = packet_get_string(&len);
1753 do_exec(s, command);
1759 session_break_req(Session *s)
1763 break_length = packet_get_int(); /* ignored */
1766 if (s->ttyfd == -1 ||
1767 tcsendbreak(s->ttyfd, 0) < 0)
1773 session_auth_agent_req(Session *s)
1775 static int called = 0;
1777 if (no_agent_forwarding_flag) {
1778 debug("session_auth_agent_req: no_agent_forwarding_flag");
1785 return auth_input_request_forwarding(s->pw);
1790 session_input_channel_req(Channel *c, const char *rtype)
1795 if ((s = session_by_channel(c->self)) == NULL) {
1796 logit("session_input_channel_req: no session %d req %.100s",
1800 debug("session_input_channel_req: session %d req %s", s->self, rtype);
1803 * a session is in LARVAL state until a shell, a command
1804 * or a subsystem is executed
1806 if (c->type == SSH_CHANNEL_LARVAL) {
1807 if (strcmp(rtype, "shell") == 0) {
1808 success = session_shell_req(s);
1809 } else if (strcmp(rtype, "exec") == 0) {
1810 success = session_exec_req(s);
1811 } else if (strcmp(rtype, "pty-req") == 0) {
1812 success = session_pty_req(s);
1813 } else if (strcmp(rtype, "x11-req") == 0) {
1814 success = session_x11_req(s);
1815 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1816 success = session_auth_agent_req(s);
1817 } else if (strcmp(rtype, "subsystem") == 0) {
1818 success = session_subsystem_req(s);
1819 } else if (strcmp(rtype, "break") == 0) {
1820 success = session_break_req(s);
1823 if (strcmp(rtype, "window-change") == 0) {
1824 success = session_window_change_req(s);
1830 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1833 fatal("session_set_fds: called for proto != 2.0");
1835 * now that have a child and a pipe to the child,
1836 * we can activate our channel and register the fd's
1838 if (s->chanid == -1)
1839 fatal("no channel for session %d", s->self);
1840 channel_set_fds(s->chanid,
1842 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1844 CHAN_SES_WINDOW_DEFAULT);
1848 * Function to perform pty cleanup. Also called if we get aborted abnormally
1849 * (e.g., due to a dropped connection).
1852 session_pty_cleanup2(void *session)
1854 Session *s = session;
1857 error("session_pty_cleanup: no session");
1863 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1865 /* Record that the user has logged out. */
1867 record_logout(s->pid, s->tty, s->pw->pw_name);
1869 /* Release the pseudo-tty. */
1871 pty_release(s->tty);
1874 * Close the server side of the socket pairs. We must do this after
1875 * the pty cleanup, so that another process doesn't get this pty
1876 * while we're still cleaning up.
1878 if (close(s->ptymaster) < 0)
1879 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
1881 /* unlink pty from session */
1886 session_pty_cleanup(void *session)
1888 PRIVSEP(session_pty_cleanup2(session));
1894 #define SSH_SIG(x) if (sig == SIG ## x) return #x
1909 return "SIG@openssh.com";
1913 session_exit_message(Session *s, int status)
1917 if ((c = channel_lookup(s->chanid)) == NULL)
1918 fatal("session_exit_message: session %d: no channel %d",
1919 s->self, s->chanid);
1920 debug("session_exit_message: session %d channel %d pid %ld",
1921 s->self, s->chanid, (long)s->pid);
1923 if (WIFEXITED(status)) {
1924 channel_request_start(s->chanid, "exit-status", 0);
1925 packet_put_int(WEXITSTATUS(status));
1927 } else if (WIFSIGNALED(status)) {
1928 channel_request_start(s->chanid, "exit-signal", 0);
1929 packet_put_cstring(sig2name(WTERMSIG(status)));
1931 packet_put_char(WCOREDUMP(status));
1932 #else /* WCOREDUMP */
1934 #endif /* WCOREDUMP */
1935 packet_put_cstring("");
1936 packet_put_cstring("");
1939 /* Some weird exit cause. Just exit. */
1940 packet_disconnect("wait returned status %04x.", status);
1943 /* disconnect channel */
1944 debug("session_exit_message: release channel %d", s->chanid);
1945 channel_cancel_cleanup(s->chanid);
1947 * emulate a write failure with 'chan_write_failed', nobody will be
1948 * interested in data we write.
1949 * Note that we must not call 'chan_read_failed', since there could
1950 * be some more data waiting in the pipe.
1952 if (c->ostate != CHAN_OUTPUT_CLOSED)
1953 chan_write_failed(c);
1958 session_close(Session *s)
1960 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
1961 if (s->ttyfd != -1) {
1962 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
1963 session_pty_cleanup(s);
1969 if (s->auth_display)
1970 xfree(s->auth_display);
1972 xfree(s->auth_data);
1974 xfree(s->auth_proto);
1976 session_proctitle(s);
1980 session_close_by_pid(pid_t pid, int status)
1982 Session *s = session_by_pid(pid);
1984 debug("session_close_by_pid: no session for pid %ld",
1988 if (s->chanid != -1)
1989 session_exit_message(s, status);
1994 * this is called when a channel dies before
1995 * the session 'child' itself dies
1998 session_close_by_channel(int id, void *arg)
2000 Session *s = session_by_channel(id);
2002 debug("session_close_by_channel: no session for id %d", id);
2005 debug("session_close_by_channel: channel %d child %ld",
2008 debug("session_close_by_channel: channel %d: has child", id);
2010 * delay detach of session, but release pty, since
2011 * the fd's to the child are already closed
2013 if (s->ttyfd != -1) {
2014 fatal_remove_cleanup(session_pty_cleanup, (void *)s);
2015 session_pty_cleanup(s);
2019 /* detach by removing callback */
2020 channel_cancel_cleanup(s->chanid);
2026 session_destroy_all(void (*closefunc)(Session *))
2029 for (i = 0; i < MAX_SESSIONS; i++) {
2030 Session *s = &sessions[i];
2032 if (closefunc != NULL)
2041 session_tty_list(void)
2043 static char buf[1024];
2048 for (i = 0; i < MAX_SESSIONS; i++) {
2049 Session *s = &sessions[i];
2050 if (s->used && s->ttyfd != -1) {
2052 if (strncmp(s->tty, "/dev/", 5) != 0) {
2053 cp = strrchr(s->tty, '/');
2054 cp = (cp == NULL) ? s->tty : cp + 1;
2059 strlcat(buf, ",", sizeof buf);
2060 strlcat(buf, cp, sizeof buf);
2064 strlcpy(buf, "notty", sizeof buf);
2069 session_proctitle(Session *s)
2072 error("no user for session %d", s->self);
2074 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2078 session_setup_x11fwd(Session *s)
2081 char display[512], auth_display[512];
2082 char hostname[MAXHOSTNAMELEN];
2084 if (no_x11_forwarding_flag) {
2085 packet_send_debug("X11 forwarding disabled in user configuration file.");
2088 if (!options.x11_forwarding) {
2089 debug("X11 forwarding disabled in server configuration file.");
2092 if (!options.xauth_location ||
2093 (stat(options.xauth_location, &st) == -1)) {
2094 packet_send_debug("No xauth program; cannot forward with spoofing.");
2097 if (options.use_login) {
2098 packet_send_debug("X11 forwarding disabled; "
2099 "not compatible with UseLogin=yes.");
2102 if (s->display != NULL) {
2103 debug("X11 display already set.");
2106 if (x11_create_display_inet(options.x11_display_offset,
2107 options.x11_use_localhost, s->single_connection,
2108 &s->display_number) == -1) {
2109 debug("x11_create_display_inet failed.");
2113 /* Set up a suitable value for the DISPLAY variable. */
2114 if (gethostname(hostname, sizeof(hostname)) < 0)
2115 fatal("gethostname: %.100s", strerror(errno));
2117 * auth_display must be used as the displayname when the
2118 * authorization entry is added with xauth(1). This will be
2119 * different than the DISPLAY string for localhost displays.
2121 if (options.x11_use_localhost) {
2122 snprintf(display, sizeof display, "localhost:%u.%u",
2123 s->display_number, s->screen);
2124 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2125 s->display_number, s->screen);
2126 s->display = xstrdup(display);
2127 s->auth_display = xstrdup(auth_display);
2129 #ifdef IPADDR_IN_DISPLAY
2131 struct in_addr my_addr;
2133 he = gethostbyname(hostname);
2135 error("Can't get IP address for X11 DISPLAY.");
2136 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2139 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2140 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2141 s->display_number, s->screen);
2143 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2144 s->display_number, s->screen);
2146 s->display = xstrdup(display);
2147 s->auth_display = xstrdup(display);
2154 do_authenticated2(Authctxt *authctxt)
2156 server_loop2(authctxt);
2158 if (options.gss_cleanup_creds)
2159 ssh_gssapi_cleanup_creds(NULL);