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.170 2003/12/23 16:12:10 jakob 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(Session *);
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 static int is_child = 0;
111 /* Name and directory of socket for authentication agent forwarding. */
112 static char *auth_sock_name = NULL;
113 static char *auth_sock_dir = NULL;
115 /* removes the agent forwarding socket */
118 auth_sock_cleanup_proc(struct passwd *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-XXXXXXXXXX", 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 /* Create the socket. */
164 sock = socket(AF_UNIX, SOCK_STREAM, 0);
166 packet_disconnect("socket: %.100s", strerror(errno));
168 /* Bind it to the name. */
169 memset(&sunaddr, 0, sizeof(sunaddr));
170 sunaddr.sun_family = AF_UNIX;
171 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
173 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
174 packet_disconnect("bind: %.100s", strerror(errno));
176 /* Restore the privileged uid. */
179 /* Start listening on the socket. */
180 if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
181 packet_disconnect("listen: %.100s", strerror(errno));
183 /* Allocate a channel for the authentication agent socket. */
184 nc = channel_new("auth socket",
185 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
186 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
187 0, "auth socket", 1);
188 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
194 do_authenticated(Authctxt *authctxt)
196 setproctitle("%s", authctxt->pw->pw_name);
199 * Cancel the alarm we set to limit the time taken for
203 if (startup_pipe != -1) {
207 /* setup the channel layer */
208 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
209 channel_permit_all_opens();
212 do_authenticated2(authctxt);
214 do_authenticated1(authctxt);
216 do_cleanup(authctxt);
220 * Prepares for an interactive session. This is called after the user has
221 * been successfully authenticated. During this message exchange, pseudo
222 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
223 * are requested, etc.
226 do_authenticated1(Authctxt *authctxt)
230 int success, type, screen_flag;
231 int enable_compression_after_reply = 0;
232 u_int proto_len, data_len, dlen, compression_level = 0;
235 s->authctxt = authctxt;
236 s->pw = authctxt->pw;
239 * We stay in this loop until the client requests to execute a shell
245 /* Get a packet from the client. */
246 type = packet_read();
248 /* Process the packet. */
250 case SSH_CMSG_REQUEST_COMPRESSION:
251 compression_level = packet_get_int();
253 if (compression_level < 1 || compression_level > 9) {
254 packet_send_debug("Received illegal compression level %d.",
258 if (!options.compression) {
259 debug2("compression disabled");
262 /* Enable compression after we have responded with SUCCESS. */
263 enable_compression_after_reply = 1;
267 case SSH_CMSG_REQUEST_PTY:
268 success = session_pty_req(s);
271 case SSH_CMSG_X11_REQUEST_FORWARDING:
272 s->auth_proto = packet_get_string(&proto_len);
273 s->auth_data = packet_get_string(&data_len);
275 screen_flag = packet_get_protocol_flags() &
276 SSH_PROTOFLAG_SCREEN_NUMBER;
277 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
279 if (packet_remaining() == 4) {
281 debug2("Buggy client: "
282 "X11 screen flag missing");
283 s->screen = packet_get_int();
288 success = session_setup_x11fwd(s);
290 xfree(s->auth_proto);
292 s->auth_proto = NULL;
297 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
298 if (no_agent_forwarding_flag || compat13) {
299 debug("Authentication agent forwarding not permitted for this authentication.");
302 debug("Received authentication agent forwarding request.");
303 success = auth_input_request_forwarding(s->pw);
306 case SSH_CMSG_PORT_FORWARD_REQUEST:
307 if (no_port_forwarding_flag) {
308 debug("Port forwarding not permitted for this authentication.");
311 if (!options.allow_tcp_forwarding) {
312 debug("Port forwarding not permitted.");
315 debug("Received TCP/IP port forwarding request.");
316 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
320 case SSH_CMSG_MAX_PACKET_SIZE:
321 if (packet_set_maxsize(packet_get_int()) > 0)
325 case SSH_CMSG_EXEC_SHELL:
326 case SSH_CMSG_EXEC_CMD:
327 if (type == SSH_CMSG_EXEC_CMD) {
328 command = packet_get_string(&dlen);
329 debug("Exec command '%.500s'", command);
341 * Any unknown messages in this phase are ignored,
342 * and a failure message is returned.
344 logit("Unknown packet type received after authentication: %d", type);
346 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
350 /* Enable compression now that we have replied if appropriate. */
351 if (enable_compression_after_reply) {
352 enable_compression_after_reply = 0;
353 packet_start_compression(compression_level);
359 * This is called to fork and execute a command when we have no tty. This
360 * will call do_child from the child, and server_loop from the parent after
361 * setting up file descriptors and such.
364 do_exec_no_pty(Session *s, const char *command)
369 int pin[2], pout[2], perr[2];
370 /* Allocate pipes for communicating with the program. */
371 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
372 packet_disconnect("Could not create pipes: %.100s",
374 #else /* USE_PIPES */
375 int inout[2], err[2];
376 /* Uses socket pairs to communicate with the program. */
377 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
378 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
379 packet_disconnect("Could not create socket pairs: %.100s",
381 #endif /* USE_PIPES */
383 fatal("do_exec_no_pty: no session");
385 session_proctitle(s);
388 if (options.use_pam) {
390 if (is_pam_password_change_required())
391 packet_disconnect("Password change required but no "
396 /* Fork the child. */
397 if ((pid = fork()) == 0) {
400 /* Child. Reinitialize the log since the pid has changed. */
401 log_init(__progname, options.log_level, options.log_facility, log_stderr);
404 * Create a new session and process group since the 4.4BSD
405 * setlogin() affects the entire process group.
408 error("setsid failed: %.100s", strerror(errno));
412 * Redirect stdin. We close the parent side of the socket
413 * pair, and make the child side the standard input.
416 if (dup2(pin[0], 0) < 0)
417 perror("dup2 stdin");
420 /* Redirect stdout. */
422 if (dup2(pout[1], 1) < 0)
423 perror("dup2 stdout");
426 /* Redirect stderr. */
428 if (dup2(perr[1], 2) < 0)
429 perror("dup2 stderr");
431 #else /* USE_PIPES */
433 * Redirect stdin, stdout, and stderr. Stdin and stdout will
434 * use the same socket, as some programs (particularly rdist)
435 * seem to depend on it.
439 if (dup2(inout[0], 0) < 0) /* stdin */
440 perror("dup2 stdin");
441 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
442 perror("dup2 stdout");
443 if (dup2(err[0], 2) < 0) /* stderr */
444 perror("dup2 stderr");
445 #endif /* USE_PIPES */
448 cray_init_job(s->pw); /* set up cray jid and tmpdir */
451 /* Do processing for the child (exec command etc). */
452 do_child(s, command);
456 signal(WJSIGNAL, cray_job_termination_handler);
460 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
463 packet_disconnect("fork failed: %.100s", strerror(errno));
465 /* Set interactive/non-interactive mode. */
466 packet_set_interactive(s->display != NULL);
468 /* We are the parent. Close the child sides of the pipes. */
474 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
476 /* Enter the interactive session. */
477 server_loop(pid, pin[1], pout[0], perr[0]);
478 /* server_loop has closed pin[1], pout[0], and perr[0]. */
480 #else /* USE_PIPES */
481 /* We are the parent. Close the child sides of the socket pairs. */
486 * Enter the interactive session. Note: server_loop must be able to
487 * handle the case that fdin and fdout are the same.
490 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
492 server_loop(pid, inout[1], inout[1], err[1]);
493 /* server_loop has closed inout[1] and err[1]. */
495 #endif /* USE_PIPES */
499 * This is called to fork and execute a command when we have a tty. This
500 * will call do_child from the child, and server_loop from the parent after
501 * setting up file descriptors, controlling tty, updating wtmp, utmp,
502 * lastlog, and other such operations.
505 do_exec_pty(Session *s, const char *command)
507 int fdout, ptyfd, ttyfd, ptymaster;
511 fatal("do_exec_pty: no session");
516 if (options.use_pam) {
517 do_pam_set_tty(s->tty);
522 /* Fork the child. */
523 if ((pid = fork()) == 0) {
526 /* Child. Reinitialize the log because the pid has changed. */
527 log_init(__progname, options.log_level, options.log_facility, log_stderr);
528 /* Close the master side of the pseudo tty. */
531 /* Make the pseudo tty our controlling tty. */
532 pty_make_controlling_tty(&ttyfd, s->tty);
534 /* Redirect stdin/stdout/stderr from the pseudo tty. */
535 if (dup2(ttyfd, 0) < 0)
536 error("dup2 stdin: %s", strerror(errno));
537 if (dup2(ttyfd, 1) < 0)
538 error("dup2 stdout: %s", strerror(errno));
539 if (dup2(ttyfd, 2) < 0)
540 error("dup2 stderr: %s", strerror(errno));
542 /* Close the extra descriptor for the pseudo tty. */
545 /* record login, etc. similar to login(1) */
547 if (!(options.use_login && command == NULL)) {
549 cray_init_job(s->pw); /* set up cray jid and tmpdir */
551 do_login(s, command);
553 # ifdef LOGIN_NEEDS_UTMPX
559 /* Do common processing for the child, such as execing the command. */
560 do_child(s, command);
564 signal(WJSIGNAL, cray_job_termination_handler);
568 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
571 packet_disconnect("fork failed: %.100s", strerror(errno));
574 /* Parent. Close the slave side of the pseudo tty. */
578 * Create another descriptor of the pty master side for use as the
579 * standard input. We could use the original descriptor, but this
580 * simplifies code in server_loop. The descriptor is bidirectional.
584 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
586 /* we keep a reference to the pty master */
587 ptymaster = dup(ptyfd);
589 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
590 s->ptymaster = ptymaster;
592 /* Enter interactive session. */
593 packet_set_interactive(1);
595 session_set_fds(s, ptyfd, fdout, -1);
597 server_loop(pid, ptyfd, fdout, -1);
598 /* server_loop _has_ closed ptyfd and fdout. */
602 #ifdef LOGIN_NEEDS_UTMPX
604 do_pre_login(Session *s)
607 struct sockaddr_storage from;
608 pid_t pid = getpid();
611 * Get IP address of client. If the connection is not a socket, let
612 * the address be 0.0.0.0.
614 memset(&from, 0, sizeof(from));
615 fromlen = sizeof(from);
616 if (packet_connection_is_on_socket()) {
617 if (getpeername(packet_get_connection_in(),
618 (struct sockaddr *) & from, &fromlen) < 0) {
619 debug("getpeername: %.100s", strerror(errno));
624 record_utmp_only(pid, s->tty, s->pw->pw_name,
625 get_remote_name_or_ip(utmp_len, options.use_dns),
626 (struct sockaddr *)&from, fromlen);
631 * This is called to fork and execute a command. If another command is
632 * to be forced, execute that instead.
635 do_exec(Session *s, const char *command)
637 if (forced_command) {
638 original_command = command;
639 command = forced_command;
640 debug("Forced command '%.900s'", command);
644 if (options.gss_authentication) {
645 temporarily_use_uid(s->pw);
646 ssh_gssapi_storecreds();
652 do_exec_pty(s, command);
654 do_exec_no_pty(s, command);
656 original_command = NULL;
660 /* administrative, login(1)-like work */
662 do_login(Session *s, const char *command)
666 struct sockaddr_storage from;
667 struct passwd * pw = s->pw;
668 pid_t pid = getpid();
671 * Get IP address of client. If the connection is not a socket, let
672 * the address be 0.0.0.0.
674 memset(&from, 0, sizeof(from));
675 fromlen = sizeof(from);
676 if (packet_connection_is_on_socket()) {
677 if (getpeername(packet_get_connection_in(),
678 (struct sockaddr *) & from, &fromlen) < 0) {
679 debug("getpeername: %.100s", strerror(errno));
684 /* Record that there was a login on that tty from the remote host. */
686 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
687 get_remote_name_or_ip(utmp_len,
689 (struct sockaddr *)&from, fromlen);
693 * If password change is needed, do it now.
694 * This needs to occur before the ~/.hushlogin check.
696 if (options.use_pam && is_pam_password_change_required()) {
697 print_pam_messages();
699 /* XXX - signal [net] parent to enable forwardings */
703 if (check_quietlogin(s, command))
707 if (options.use_pam && !is_pam_password_change_required())
708 print_pam_messages();
711 /* display post-login message */
712 if (buffer_len(&loginmsg) > 0) {
713 buffer_append(&loginmsg, "\0", 1);
714 printf("%s\n", (char *)buffer_ptr(&loginmsg));
716 buffer_free(&loginmsg);
718 #ifndef NO_SSH_LASTLOG
719 if (options.print_lastlog && s->last_login_time != 0) {
720 time_string = ctime(&s->last_login_time);
721 if (strchr(time_string, '\n'))
722 *strchr(time_string, '\n') = 0;
723 if (strcmp(s->hostname, "") == 0)
724 printf("Last login: %s\r\n", time_string);
726 printf("Last login: %s from %s\r\n", time_string,
729 #endif /* NO_SSH_LASTLOG */
735 * Display the message of the day.
743 if (options.print_motd) {
744 #ifdef HAVE_LOGIN_CAP
745 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
748 f = fopen("/etc/motd", "r");
751 while (fgets(buf, sizeof(buf), f))
760 * Check for quiet login, either .hushlogin or command given.
763 check_quietlogin(Session *s, const char *command)
766 struct passwd *pw = s->pw;
769 /* Return 1 if .hushlogin exists or a command given. */
772 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
773 #ifdef HAVE_LOGIN_CAP
774 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
777 if (stat(buf, &st) >= 0)
784 * Sets the value of the given variable in the environment. If the variable
785 * already exists, its value is overriden.
788 child_set_env(char ***envp, u_int *envsizep, const char *name,
796 * If we're passed an uninitialized list, allocate a single null
797 * entry before continuing.
799 if (*envp == NULL && *envsizep == 0) {
800 *envp = xmalloc(sizeof(char *));
806 * Find the slot where the value should be stored. If the variable
807 * already exists, we reuse the slot; otherwise we append a new slot
808 * at the end of the array, expanding if necessary.
811 namelen = strlen(name);
812 for (i = 0; env[i]; i++)
813 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
816 /* Reuse the slot. */
819 /* New variable. Expand if necessary. */
821 if (i >= envsize - 1) {
823 fatal("child_set_env: too many env vars");
825 env = (*envp) = xrealloc(env, envsize * sizeof(char *));
828 /* Need to set the NULL pointer at end of array beyond the new slot. */
832 /* Allocate space and format the variable in the appropriate slot. */
833 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
834 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
838 * Reads environment variables from the given file and adds/overrides them
839 * into the environment. If the file does not exist, this does nothing.
840 * Otherwise, it must consist of empty lines, comments (line starts with '#')
841 * and assignments of the form name=value. No other forms are allowed.
844 read_environment_file(char ***env, u_int *envsize,
845 const char *filename)
852 f = fopen(filename, "r");
856 while (fgets(buf, sizeof(buf), f)) {
858 fatal("Too many lines in environment file %s", filename);
859 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
861 if (!*cp || *cp == '#' || *cp == '\n')
863 if (strchr(cp, '\n'))
864 *strchr(cp, '\n') = '\0';
865 value = strchr(cp, '=');
867 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
872 * Replace the equals sign by nul, and advance value to
877 child_set_env(env, envsize, cp, value);
882 #ifdef HAVE_ETC_DEFAULT_LOGIN
884 * Return named variable from specified environment, or NULL if not present.
887 child_get_env(char **env, const char *name)
893 for (i=0; env[i] != NULL; i++)
894 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
895 return(env[i] + len + 1);
900 * Read /etc/default/login.
901 * We pick up the PATH (or SUPATH for root) and UMASK.
904 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
906 char **tmpenv = NULL, *var;
907 u_int i, tmpenvsize = 0;
911 * We don't want to copy the whole file to the child's environment,
912 * so we use a temporary environment and copy the variables we're
915 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
921 var = child_get_env(tmpenv, "SUPATH");
923 var = child_get_env(tmpenv, "PATH");
925 child_set_env(env, envsize, "PATH", var);
927 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
928 if (sscanf(var, "%5lo", &mask) == 1)
931 for (i = 0; tmpenv[i] != NULL; i++)
935 #endif /* HAVE_ETC_DEFAULT_LOGIN */
937 void copy_environment(char **source, char ***env, u_int *envsize)
939 char *var_name, *var_val;
945 for(i = 0; source[i] != NULL; i++) {
946 var_name = xstrdup(source[i]);
947 if ((var_val = strstr(var_name, "=")) == NULL) {
953 debug3("Copy environment: %s=%s", var_name, var_val);
954 child_set_env(env, envsize, var_name, var_val);
961 do_setup_env(Session *s, const char *shell)
965 char **env, *laddr, *path = NULL;
966 struct passwd *pw = s->pw;
968 /* Initialize the environment. */
970 env = xmalloc(envsize * sizeof(char *));
975 * The Windows environment contains some setting which are
976 * important for a running system. They must not be dropped.
978 copy_environment(environ, &env, &envsize);
982 /* Allow any GSSAPI methods that we've used to alter
983 * the childs environment as they see fit
985 ssh_gssapi_do_child(&env, &envsize);
988 if (!options.use_login) {
989 /* Set basic environment. */
990 child_set_env(&env, &envsize, "USER", pw->pw_name);
991 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
993 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
995 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
996 #ifdef HAVE_LOGIN_CAP
997 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
998 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1000 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1001 #else /* HAVE_LOGIN_CAP */
1002 # ifndef HAVE_CYGWIN
1004 * There's no standard path on Windows. The path contains
1005 * important components pointing to the system directories,
1006 * needed for loading shared libraries. So the path better
1007 * remains intact here.
1009 # ifdef HAVE_ETC_DEFAULT_LOGIN
1010 read_etc_default_login(&env, &envsize, pw->pw_uid);
1011 path = child_get_env(env, "PATH");
1012 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1013 if (path == NULL || *path == '\0') {
1014 child_set_env(&env, &envsize, "PATH",
1015 s->pw->pw_uid == 0 ?
1016 SUPERUSER_PATH : _PATH_STDPATH);
1018 # endif /* HAVE_CYGWIN */
1019 #endif /* HAVE_LOGIN_CAP */
1021 snprintf(buf, sizeof buf, "%.200s/%.50s",
1022 _PATH_MAILDIR, pw->pw_name);
1023 child_set_env(&env, &envsize, "MAIL", buf);
1025 /* Normal systems set SHELL by default. */
1026 child_set_env(&env, &envsize, "SHELL", shell);
1029 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1031 /* Set custom environment options from RSA authentication. */
1032 if (!options.use_login) {
1033 while (custom_environment) {
1034 struct envstring *ce = custom_environment;
1037 for (i = 0; str[i] != '=' && str[i]; i++)
1039 if (str[i] == '=') {
1041 child_set_env(&env, &envsize, str, str + i + 1);
1043 custom_environment = ce->next;
1049 /* SSH_CLIENT deprecated */
1050 snprintf(buf, sizeof buf, "%.50s %d %d",
1051 get_remote_ipaddr(), get_remote_port(), get_local_port());
1052 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1054 laddr = get_local_ipaddr(packet_get_connection_in());
1055 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1056 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1058 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1061 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1063 child_set_env(&env, &envsize, "TERM", s->term);
1065 child_set_env(&env, &envsize, "DISPLAY", s->display);
1066 if (original_command)
1067 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1071 if (cray_tmpdir[0] != '\0')
1072 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1073 #endif /* _UNICOS */
1079 if ((cp = getenv("AUTHSTATE")) != NULL)
1080 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1081 if ((cp = getenv("KRB5CCNAME")) != NULL)
1082 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1083 read_environment_file(&env, &envsize, "/etc/environment");
1087 if (s->authctxt->krb5_ticket_file)
1088 child_set_env(&env, &envsize, "KRB5CCNAME",
1089 s->authctxt->krb5_ticket_file);
1093 * Pull in any environment variables that may have
1096 if (options.use_pam) {
1099 p = fetch_pam_child_environment();
1100 copy_environment(p, &env, &envsize);
1101 free_pam_environment(p);
1103 p = fetch_pam_environment();
1104 copy_environment(p, &env, &envsize);
1105 free_pam_environment(p);
1107 #endif /* USE_PAM */
1109 if (auth_sock_name != NULL)
1110 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1113 /* read $HOME/.ssh/environment. */
1114 if (options.permit_user_env && !options.use_login) {
1115 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1116 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1117 read_environment_file(&env, &envsize, buf);
1120 /* dump the environment */
1121 fprintf(stderr, "Environment:\n");
1122 for (i = 0; env[i]; i++)
1123 fprintf(stderr, " %.200s\n", env[i]);
1129 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1130 * first in this order).
1133 do_rc_files(Session *s, const char *shell)
1141 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1143 /* ignore _PATH_SSH_USER_RC for subsystems */
1144 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1145 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1146 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1148 fprintf(stderr, "Running %s\n", cmd);
1149 f = popen(cmd, "w");
1152 fprintf(f, "%s %s\n", s->auth_proto,
1156 fprintf(stderr, "Could not run %s\n",
1158 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1160 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1161 _PATH_SSH_SYSTEM_RC);
1162 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1165 fprintf(f, "%s %s\n", s->auth_proto,
1169 fprintf(stderr, "Could not run %s\n",
1170 _PATH_SSH_SYSTEM_RC);
1171 } else if (do_xauth && options.xauth_location != NULL) {
1172 /* Add authority data to .Xauthority if appropriate. */
1175 "Running %.500s remove %.100s\n",
1176 options.xauth_location, s->auth_display);
1178 "%.500s add %.100s %.100s %.100s\n",
1179 options.xauth_location, s->auth_display,
1180 s->auth_proto, s->auth_data);
1182 snprintf(cmd, sizeof cmd, "%s -q -",
1183 options.xauth_location);
1184 f = popen(cmd, "w");
1186 fprintf(f, "remove %s\n",
1188 fprintf(f, "add %s %s %s\n",
1189 s->auth_display, s->auth_proto,
1193 fprintf(stderr, "Could not run %s\n",
1200 do_nologin(struct passwd *pw)
1205 #ifdef HAVE_LOGIN_CAP
1206 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1207 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1208 _PATH_NOLOGIN), "r");
1211 f = fopen(_PATH_NOLOGIN, "r");
1214 /* /etc/nologin exists. Print its contents and exit. */
1215 logit("User %.100s not allowed because %s exists",
1216 pw->pw_name, _PATH_NOLOGIN);
1217 while (fgets(buf, sizeof(buf), f))
1225 /* Set login name, uid, gid, and groups. */
1227 do_setusercontext(struct passwd *pw)
1230 if (getuid() == 0 || geteuid() == 0)
1231 #endif /* HAVE_CYGWIN */
1234 #ifdef HAVE_SETPCRED
1235 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1236 fatal("Failed to set process credentials");
1237 #endif /* HAVE_SETPCRED */
1238 #ifdef HAVE_LOGIN_CAP
1242 if (setusercontext(lc, pw, pw->pw_uid,
1243 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1244 perror("unable to set user context");
1248 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1249 /* Sets login uid for accounting */
1250 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1251 error("setluid: %s", strerror(errno));
1252 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1254 if (setlogin(pw->pw_name) < 0)
1255 error("setlogin failed: %s", strerror(errno));
1256 if (setgid(pw->pw_gid) < 0) {
1260 /* Initialize the group list. */
1261 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1262 perror("initgroups");
1268 * PAM credentials may take the form of supplementary groups.
1269 * These will have been wiped by the above initgroups() call.
1270 * Reestablish them here.
1272 if (options.use_pam) {
1276 # endif /* USE_PAM */
1277 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1278 irix_setusercontext(pw);
1279 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1283 /* Permanently switch to the desired uid. */
1284 permanently_set_uid(pw);
1291 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1292 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1296 launch_login(struct passwd *pw, const char *hostname)
1298 /* Launch login(1). */
1300 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1301 #ifdef xxxLOGIN_NEEDS_TERM
1302 (s->term ? s->term : "unknown"),
1303 #endif /* LOGIN_NEEDS_TERM */
1304 #ifdef LOGIN_NO_ENDOPT
1305 "-p", "-f", pw->pw_name, (char *)NULL);
1307 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1310 /* Login couldn't be executed, die. */
1317 * Performs common processing for the child, such as setting up the
1318 * environment, closing extra file descriptors, setting the user and group
1319 * ids, and executing the command or shell.
1322 do_child(Session *s, const char *command)
1324 extern char **environ;
1327 const char *shell, *shell0, *hostname = NULL;
1328 struct passwd *pw = s->pw;
1331 /* remove hostkey from the child's memory */
1332 destroy_sensitive_data();
1334 /* login(1) is only called if we execute the login shell */
1335 if (options.use_login && command != NULL)
1336 options.use_login = 0;
1339 cray_setup(pw->pw_uid, pw->pw_name, command);
1340 #endif /* _UNICOS */
1343 * Login(1) does this as well, and it needs uid 0 for the "-h"
1344 * switch, so we let login(1) to this for us.
1346 if (!options.use_login) {
1348 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1349 if (!check_quietlogin(s, command))
1351 #else /* HAVE_OSF_SIA */
1353 do_setusercontext(pw);
1354 #endif /* HAVE_OSF_SIA */
1358 * Get the shell from the password data. An empty shell field is
1359 * legal, and means /bin/sh.
1361 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1364 * Make sure $SHELL points to the shell from the password file,
1365 * even if shell is overridden from login.conf
1367 env = do_setup_env(s, shell);
1369 #ifdef HAVE_LOGIN_CAP
1370 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1373 /* we have to stash the hostname before we close our socket. */
1374 if (options.use_login)
1375 hostname = get_remote_name_or_ip(utmp_len,
1378 * Close the connection descriptors; note that this is the child, and
1379 * the server will still have the socket open, and it is important
1380 * that we do not shutdown it. Note that the descriptors cannot be
1381 * closed before building the environment, as we call
1382 * get_remote_ipaddr there.
1384 if (packet_get_connection_in() == packet_get_connection_out())
1385 close(packet_get_connection_in());
1387 close(packet_get_connection_in());
1388 close(packet_get_connection_out());
1391 * Close all descriptors related to channels. They will still remain
1392 * open in the parent.
1394 /* XXX better use close-on-exec? -markus */
1395 channel_close_all();
1398 * Close any extra file descriptors. Note that there may still be
1399 * descriptors left by system functions. They will be closed later.
1404 * Close any extra open file descriptors so that we don\'t have them
1405 * hanging around in clients. Note that we want to do this after
1406 * initgroups, because at least on Solaris 2.3 it leaves file
1409 for (i = 3; i < 64; i++)
1413 * Must take new environment into use so that .ssh/rc,
1414 * /etc/ssh/sshrc and xauth are run in the proper environment.
1418 #if defined(HEIMDAL) && defined(AFS)
1420 * At this point, we check to see if AFS is active and if we have
1421 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1422 * if we can (and need to) extend the ticket into an AFS token. If
1423 * we don't do this, we run into potential problems if the user's
1424 * home directory is in AFS and it's not world-readable.
1427 if (options.kerberos_get_afs_token && k_hasafs() &&
1428 (s->authctxt->krb5_ctx != NULL)) {
1431 debug("Getting AFS token");
1435 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1436 krb5_afslog(s->authctxt->krb5_ctx,
1437 s->authctxt->krb5_fwd_ccache, cell, NULL);
1439 krb5_afslog_home(s->authctxt->krb5_ctx,
1440 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1444 /* Change current directory to the user\'s home directory. */
1445 if (chdir(pw->pw_dir) < 0) {
1446 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1447 pw->pw_dir, strerror(errno));
1448 #ifdef HAVE_LOGIN_CAP
1449 if (login_getcapbool(lc, "requirehome", 0))
1454 if (!options.use_login)
1455 do_rc_files(s, shell);
1457 /* restore SIGPIPE for child */
1458 signal(SIGPIPE, SIG_DFL);
1460 if (options.use_login) {
1461 launch_login(pw, hostname);
1465 /* Get the last component of the shell name. */
1466 if ((shell0 = strrchr(shell, '/')) != NULL)
1472 * If we have no command, execute the shell. In this case, the shell
1473 * name to be passed in argv[0] is preceded by '-' to indicate that
1474 * this is a login shell.
1479 /* Start the shell. Set initial character to '-'. */
1482 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1483 >= sizeof(argv0) - 1) {
1489 /* Execute the shell. */
1492 execve(shell, argv, env);
1494 /* Executing the shell failed. */
1499 * Execute the command using the user's shell. This uses the -c
1500 * option to execute the command.
1502 argv[0] = (char *) shell0;
1504 argv[2] = (char *) command;
1506 execve(shell, argv, env);
1515 static int did_init = 0;
1517 debug("session_new: init");
1518 for (i = 0; i < MAX_SESSIONS; i++) {
1519 sessions[i].used = 0;
1523 for (i = 0; i < MAX_SESSIONS; i++) {
1524 Session *s = &sessions[i];
1526 memset(s, 0, sizeof(*s));
1532 debug("session_new: session %d", i);
1543 for (i = 0; i < MAX_SESSIONS; i++) {
1544 Session *s = &sessions[i];
1545 debug("dump: used %d session %d %p channel %d pid %ld",
1555 session_open(Authctxt *authctxt, int chanid)
1557 Session *s = session_new();
1558 debug("session_open: channel %d", chanid);
1560 error("no more sessions");
1563 s->authctxt = authctxt;
1564 s->pw = authctxt->pw;
1565 if (s->pw == NULL || !authctxt->valid)
1566 fatal("no user for session %d", s->self);
1567 debug("session_open: session %d: link with channel %d", s->self, chanid);
1573 session_by_tty(char *tty)
1576 for (i = 0; i < MAX_SESSIONS; i++) {
1577 Session *s = &sessions[i];
1578 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1579 debug("session_by_tty: session %d tty %s", i, tty);
1583 debug("session_by_tty: unknown tty %.100s", tty);
1589 session_by_channel(int id)
1592 for (i = 0; i < MAX_SESSIONS; i++) {
1593 Session *s = &sessions[i];
1594 if (s->used && s->chanid == id) {
1595 debug("session_by_channel: session %d channel %d", i, id);
1599 debug("session_by_channel: unknown channel %d", id);
1605 session_by_pid(pid_t pid)
1608 debug("session_by_pid: pid %ld", (long)pid);
1609 for (i = 0; i < MAX_SESSIONS; i++) {
1610 Session *s = &sessions[i];
1611 if (s->used && s->pid == pid)
1614 error("session_by_pid: unknown pid %ld", (long)pid);
1620 session_window_change_req(Session *s)
1622 s->col = packet_get_int();
1623 s->row = packet_get_int();
1624 s->xpixel = packet_get_int();
1625 s->ypixel = packet_get_int();
1627 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1632 session_pty_req(Session *s)
1638 debug("Allocating a pty not permitted for this authentication.");
1641 if (s->ttyfd != -1) {
1642 packet_disconnect("Protocol error: you already have a pty.");
1645 /* Get the time and hostname when the user last logged in. */
1646 if (options.print_lastlog) {
1647 s->hostname[0] = '\0';
1648 s->last_login_time = get_last_login_time(s->pw->pw_uid,
1649 s->pw->pw_name, s->hostname, sizeof(s->hostname));
1652 s->term = packet_get_string(&len);
1655 s->col = packet_get_int();
1656 s->row = packet_get_int();
1658 s->row = packet_get_int();
1659 s->col = packet_get_int();
1661 s->xpixel = packet_get_int();
1662 s->ypixel = packet_get_int();
1664 if (strcmp(s->term, "") == 0) {
1669 /* Allocate a pty and open it. */
1670 debug("Allocating pty.");
1671 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1677 error("session_pty_req: session %d alloc failed", s->self);
1680 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1682 /* for SSH1 the tty modes length is not given */
1684 n_bytes = packet_remaining();
1685 tty_parse_modes(s->ttyfd, &n_bytes);
1688 pty_setowner(s->pw, s->tty);
1690 /* Set window size from the packet. */
1691 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1694 session_proctitle(s);
1699 session_subsystem_req(Session *s)
1704 char *cmd, *subsys = packet_get_string(&len);
1708 logit("subsystem request for %.100s", subsys);
1710 for (i = 0; i < options.num_subsystems; i++) {
1711 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1712 cmd = options.subsystem_command[i];
1713 if (stat(cmd, &st) < 0) {
1714 error("subsystem: cannot stat %s: %s", cmd,
1718 debug("subsystem: exec() %s", cmd);
1719 s->is_subsystem = 1;
1727 logit("subsystem request for %.100s failed, subsystem not found",
1735 session_x11_req(Session *s)
1739 s->single_connection = packet_get_char();
1740 s->auth_proto = packet_get_string(NULL);
1741 s->auth_data = packet_get_string(NULL);
1742 s->screen = packet_get_int();
1745 success = session_setup_x11fwd(s);
1747 xfree(s->auth_proto);
1748 xfree(s->auth_data);
1749 s->auth_proto = NULL;
1750 s->auth_data = NULL;
1756 session_shell_req(Session *s)
1764 session_exec_req(Session *s)
1767 char *command = packet_get_string(&len);
1769 do_exec(s, command);
1775 session_break_req(Session *s)
1779 break_length = packet_get_int(); /* ignored */
1782 if (s->ttyfd == -1 ||
1783 tcsendbreak(s->ttyfd, 0) < 0)
1789 session_auth_agent_req(Session *s)
1791 static int called = 0;
1793 if (no_agent_forwarding_flag) {
1794 debug("session_auth_agent_req: no_agent_forwarding_flag");
1801 return auth_input_request_forwarding(s->pw);
1806 session_input_channel_req(Channel *c, const char *rtype)
1811 if ((s = session_by_channel(c->self)) == NULL) {
1812 logit("session_input_channel_req: no session %d req %.100s",
1816 debug("session_input_channel_req: session %d req %s", s->self, rtype);
1819 * a session is in LARVAL state until a shell, a command
1820 * or a subsystem is executed
1822 if (c->type == SSH_CHANNEL_LARVAL) {
1823 if (strcmp(rtype, "shell") == 0) {
1824 success = session_shell_req(s);
1825 } else if (strcmp(rtype, "exec") == 0) {
1826 success = session_exec_req(s);
1827 } else if (strcmp(rtype, "pty-req") == 0) {
1828 success = session_pty_req(s);
1829 } else if (strcmp(rtype, "x11-req") == 0) {
1830 success = session_x11_req(s);
1831 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1832 success = session_auth_agent_req(s);
1833 } else if (strcmp(rtype, "subsystem") == 0) {
1834 success = session_subsystem_req(s);
1835 } else if (strcmp(rtype, "break") == 0) {
1836 success = session_break_req(s);
1839 if (strcmp(rtype, "window-change") == 0) {
1840 success = session_window_change_req(s);
1846 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1849 fatal("session_set_fds: called for proto != 2.0");
1851 * now that have a child and a pipe to the child,
1852 * we can activate our channel and register the fd's
1854 if (s->chanid == -1)
1855 fatal("no channel for session %d", s->self);
1856 channel_set_fds(s->chanid,
1858 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1860 CHAN_SES_WINDOW_DEFAULT);
1864 * Function to perform pty cleanup. Also called if we get aborted abnormally
1865 * (e.g., due to a dropped connection).
1868 session_pty_cleanup2(Session *s)
1871 error("session_pty_cleanup: no session");
1877 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1879 /* Record that the user has logged out. */
1881 record_logout(s->pid, s->tty, s->pw->pw_name);
1883 /* Release the pseudo-tty. */
1885 pty_release(s->tty);
1888 * Close the server side of the socket pairs. We must do this after
1889 * the pty cleanup, so that another process doesn't get this pty
1890 * while we're still cleaning up.
1892 if (close(s->ptymaster) < 0)
1893 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
1895 /* unlink pty from session */
1900 session_pty_cleanup(Session *s)
1902 PRIVSEP(session_pty_cleanup2(s));
1908 #define SSH_SIG(x) if (sig == SIG ## x) return #x
1923 return "SIG@openssh.com";
1927 session_exit_message(Session *s, int status)
1931 if ((c = channel_lookup(s->chanid)) == NULL)
1932 fatal("session_exit_message: session %d: no channel %d",
1933 s->self, s->chanid);
1934 debug("session_exit_message: session %d channel %d pid %ld",
1935 s->self, s->chanid, (long)s->pid);
1937 if (WIFEXITED(status)) {
1938 channel_request_start(s->chanid, "exit-status", 0);
1939 packet_put_int(WEXITSTATUS(status));
1941 } else if (WIFSIGNALED(status)) {
1942 channel_request_start(s->chanid, "exit-signal", 0);
1943 packet_put_cstring(sig2name(WTERMSIG(status)));
1945 packet_put_char(WCOREDUMP(status));
1946 #else /* WCOREDUMP */
1948 #endif /* WCOREDUMP */
1949 packet_put_cstring("");
1950 packet_put_cstring("");
1953 /* Some weird exit cause. Just exit. */
1954 packet_disconnect("wait returned status %04x.", status);
1957 /* disconnect channel */
1958 debug("session_exit_message: release channel %d", s->chanid);
1959 channel_cancel_cleanup(s->chanid);
1961 * emulate a write failure with 'chan_write_failed', nobody will be
1962 * interested in data we write.
1963 * Note that we must not call 'chan_read_failed', since there could
1964 * be some more data waiting in the pipe.
1966 if (c->ostate != CHAN_OUTPUT_CLOSED)
1967 chan_write_failed(c);
1972 session_close(Session *s)
1974 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
1976 session_pty_cleanup(s);
1981 if (s->auth_display)
1982 xfree(s->auth_display);
1984 xfree(s->auth_data);
1986 xfree(s->auth_proto);
1988 session_proctitle(s);
1992 session_close_by_pid(pid_t pid, int status)
1994 Session *s = session_by_pid(pid);
1996 debug("session_close_by_pid: no session for pid %ld",
2000 if (s->chanid != -1)
2001 session_exit_message(s, status);
2006 * this is called when a channel dies before
2007 * the session 'child' itself dies
2010 session_close_by_channel(int id, void *arg)
2012 Session *s = session_by_channel(id);
2014 debug("session_close_by_channel: no session for id %d", id);
2017 debug("session_close_by_channel: channel %d child %ld",
2020 debug("session_close_by_channel: channel %d: has child", id);
2022 * delay detach of session, but release pty, since
2023 * the fd's to the child are already closed
2026 session_pty_cleanup(s);
2029 /* detach by removing callback */
2030 channel_cancel_cleanup(s->chanid);
2036 session_destroy_all(void (*closefunc)(Session *))
2039 for (i = 0; i < MAX_SESSIONS; i++) {
2040 Session *s = &sessions[i];
2042 if (closefunc != NULL)
2051 session_tty_list(void)
2053 static char buf[1024];
2058 for (i = 0; i < MAX_SESSIONS; i++) {
2059 Session *s = &sessions[i];
2060 if (s->used && s->ttyfd != -1) {
2062 if (strncmp(s->tty, "/dev/", 5) != 0) {
2063 cp = strrchr(s->tty, '/');
2064 cp = (cp == NULL) ? s->tty : cp + 1;
2069 strlcat(buf, ",", sizeof buf);
2070 strlcat(buf, cp, sizeof buf);
2074 strlcpy(buf, "notty", sizeof buf);
2079 session_proctitle(Session *s)
2082 error("no user for session %d", s->self);
2084 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2088 session_setup_x11fwd(Session *s)
2091 char display[512], auth_display[512];
2092 char hostname[MAXHOSTNAMELEN];
2094 if (no_x11_forwarding_flag) {
2095 packet_send_debug("X11 forwarding disabled in user configuration file.");
2098 if (!options.x11_forwarding) {
2099 debug("X11 forwarding disabled in server configuration file.");
2102 if (!options.xauth_location ||
2103 (stat(options.xauth_location, &st) == -1)) {
2104 packet_send_debug("No xauth program; cannot forward with spoofing.");
2107 if (options.use_login) {
2108 packet_send_debug("X11 forwarding disabled; "
2109 "not compatible with UseLogin=yes.");
2112 if (s->display != NULL) {
2113 debug("X11 display already set.");
2116 if (x11_create_display_inet(options.x11_display_offset,
2117 options.x11_use_localhost, s->single_connection,
2118 &s->display_number) == -1) {
2119 debug("x11_create_display_inet failed.");
2123 /* Set up a suitable value for the DISPLAY variable. */
2124 if (gethostname(hostname, sizeof(hostname)) < 0)
2125 fatal("gethostname: %.100s", strerror(errno));
2127 * auth_display must be used as the displayname when the
2128 * authorization entry is added with xauth(1). This will be
2129 * different than the DISPLAY string for localhost displays.
2131 if (options.x11_use_localhost) {
2132 snprintf(display, sizeof display, "localhost:%u.%u",
2133 s->display_number, s->screen);
2134 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2135 s->display_number, s->screen);
2136 s->display = xstrdup(display);
2137 s->auth_display = xstrdup(auth_display);
2139 #ifdef IPADDR_IN_DISPLAY
2141 struct in_addr my_addr;
2143 he = gethostbyname(hostname);
2145 error("Can't get IP address for X11 DISPLAY.");
2146 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2149 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2150 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2151 s->display_number, s->screen);
2153 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2154 s->display_number, s->screen);
2156 s->display = xstrdup(display);
2157 s->auth_display = xstrdup(display);
2164 do_authenticated2(Authctxt *authctxt)
2166 server_loop2(authctxt);
2170 do_cleanup(Authctxt *authctxt)
2172 static int called = 0;
2174 debug("do_cleanup");
2176 /* no cleanup if we're in the child for login shell */
2180 /* avoid double cleanup */
2185 if (authctxt == NULL)
2188 if (options.kerberos_ticket_cleanup &&
2190 krb5_cleanup_proc(authctxt);
2194 if (compat20 && options.gss_cleanup_creds)
2195 ssh_gssapi_cleanup_creds();
2199 if (options.use_pam) {
2201 sshpam_thread_cleanup();
2205 /* remove agent socket */
2206 auth_sock_cleanup_proc(authctxt->pw);
2209 * Cleanup ptys/utmp only if privsep is disabled,
2210 * or if running in monitor.
2212 if (!use_privsep || mm_is_monitor())
2213 session_destroy_all(session_pty_cleanup2);