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.181 2004/12/23 17:35:48 markus Exp $");
51 #include "auth-options.h"
52 #include "pathnames.h"
56 #include "serverloop.h"
59 #include "monitor_wrap.h"
61 #if defined(KRB5) && defined(USE_AFS)
71 Session *session_new(void);
72 void session_set_fds(Session *, int, int, int);
73 void session_pty_cleanup(Session *);
74 void session_proctitle(Session *);
75 int session_setup_x11fwd(Session *);
76 void do_exec_pty(Session *, const char *);
77 void do_exec_no_pty(Session *, const char *);
78 void do_exec(Session *, const char *);
79 void do_login(Session *, const char *);
80 #ifdef LOGIN_NEEDS_UTMPX
81 static void do_pre_login(Session *s);
83 void do_child(Session *, const char *);
85 int check_quietlogin(Session *, const char *);
87 static void do_authenticated1(Authctxt *);
88 static void do_authenticated2(Authctxt *);
90 static int session_pty_req(Session *);
93 static void execute_session_hook(char* prog, Authctxt *authctxt,
94 int startup, int save);
98 extern ServerOptions options;
99 extern char *__progname;
100 extern int log_stderr;
101 extern int debug_flag;
102 extern u_int utmp_len;
103 extern int startup_pipe;
104 extern void destroy_sensitive_data(void);
105 extern Buffer loginmsg;
107 /* original command from peer. */
108 const char *original_command = NULL;
111 #define MAX_SESSIONS 10
112 Session sessions[MAX_SESSIONS];
114 #ifdef HAVE_LOGIN_CAP
118 static int is_child = 0;
120 /* Name and directory of socket for authentication agent forwarding. */
121 static char *auth_sock_name = NULL;
122 static char *auth_sock_dir = NULL;
124 /* removes the agent forwarding socket */
127 auth_sock_cleanup_proc(struct passwd *pw)
129 if (auth_sock_name != NULL) {
130 temporarily_use_uid(pw);
131 unlink(auth_sock_name);
132 rmdir(auth_sock_dir);
133 auth_sock_name = NULL;
139 auth_input_request_forwarding(struct passwd * pw)
143 struct sockaddr_un sunaddr;
145 if (auth_sock_name != NULL) {
146 error("authentication forwarding requested twice.");
150 /* Temporarily drop privileged uid for mkdir/bind. */
151 temporarily_use_uid(pw);
153 /* Allocate a buffer for the socket name, and format the name. */
154 auth_sock_name = xmalloc(MAXPATHLEN);
155 auth_sock_dir = xmalloc(MAXPATHLEN);
156 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
158 /* Create private directory for socket */
159 if (mkdtemp(auth_sock_dir) == NULL) {
160 packet_send_debug("Agent forwarding disabled: "
161 "mkdtemp() failed: %.100s", strerror(errno));
163 xfree(auth_sock_name);
164 xfree(auth_sock_dir);
165 auth_sock_name = NULL;
166 auth_sock_dir = NULL;
169 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
170 auth_sock_dir, (long) getpid());
172 /* Create the socket. */
173 sock = socket(AF_UNIX, SOCK_STREAM, 0);
175 packet_disconnect("socket: %.100s", strerror(errno));
177 /* Bind it to the name. */
178 memset(&sunaddr, 0, sizeof(sunaddr));
179 sunaddr.sun_family = AF_UNIX;
180 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
182 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
183 packet_disconnect("bind: %.100s", strerror(errno));
185 /* Restore the privileged uid. */
188 /* Start listening on the socket. */
189 if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
190 packet_disconnect("listen: %.100s", strerror(errno));
192 /* Allocate a channel for the authentication agent socket. */
193 nc = channel_new("auth socket",
194 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
195 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
196 0, "auth socket", 1);
197 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
202 display_loginmsg(void)
204 if (buffer_len(&loginmsg) > 0) {
205 buffer_append(&loginmsg, "\0", 1);
206 printf("%s", (char *)buffer_ptr(&loginmsg));
207 buffer_clear(&loginmsg);
212 do_authenticated(Authctxt *authctxt)
214 setproctitle("%s", authctxt->pw->pw_name);
217 * Cancel the alarm we set to limit the time taken for
221 if (startup_pipe != -1) {
225 /* setup the channel layer */
226 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
227 channel_permit_all_opens();
230 do_authenticated2(authctxt);
232 do_authenticated1(authctxt);
235 if (options.session_hooks_allow &&
236 options.session_hooks_shutdown_cmd)
238 execute_session_hook(options.session_hooks_shutdown_cmd,
240 /* startup = */ 0, /* save = */ 0);
242 if (authctxt->session_env_file)
244 free(authctxt->session_env_file);
249 do_cleanup(authctxt);
253 * Prepares for an interactive session. This is called after the user has
254 * been successfully authenticated. During this message exchange, pseudo
255 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
256 * are requested, etc.
259 do_authenticated1(Authctxt *authctxt)
263 int success, type, screen_flag;
264 int enable_compression_after_reply = 0;
265 u_int proto_len, data_len, dlen, compression_level = 0;
269 error("no more sessions");
272 s->authctxt = authctxt;
273 s->pw = authctxt->pw;
276 * We stay in this loop until the client requests to execute a shell
282 /* Get a packet from the client. */
283 type = packet_read();
285 /* Process the packet. */
287 case SSH_CMSG_REQUEST_COMPRESSION:
288 compression_level = packet_get_int();
290 if (compression_level < 1 || compression_level > 9) {
291 packet_send_debug("Received invalid compression level %d.",
295 if (!options.compression) {
296 debug2("compression disabled");
299 /* Enable compression after we have responded with SUCCESS. */
300 enable_compression_after_reply = 1;
304 case SSH_CMSG_REQUEST_PTY:
305 success = session_pty_req(s);
308 case SSH_CMSG_X11_REQUEST_FORWARDING:
309 s->auth_proto = packet_get_string(&proto_len);
310 s->auth_data = packet_get_string(&data_len);
312 screen_flag = packet_get_protocol_flags() &
313 SSH_PROTOFLAG_SCREEN_NUMBER;
314 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
316 if (packet_remaining() == 4) {
318 debug2("Buggy client: "
319 "X11 screen flag missing");
320 s->screen = packet_get_int();
325 success = session_setup_x11fwd(s);
327 xfree(s->auth_proto);
329 s->auth_proto = NULL;
334 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
335 if (no_agent_forwarding_flag || compat13) {
336 debug("Authentication agent forwarding not permitted for this authentication.");
339 debug("Received authentication agent forwarding request.");
340 success = auth_input_request_forwarding(s->pw);
343 case SSH_CMSG_PORT_FORWARD_REQUEST:
344 if (no_port_forwarding_flag) {
345 debug("Port forwarding not permitted for this authentication.");
348 if (!options.allow_tcp_forwarding) {
349 debug("Port forwarding not permitted.");
352 debug("Received TCP/IP port forwarding request.");
353 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
357 case SSH_CMSG_MAX_PACKET_SIZE:
358 if (packet_set_maxsize(packet_get_int()) > 0)
362 case SSH_CMSG_EXEC_SHELL:
363 case SSH_CMSG_EXEC_CMD:
364 if (type == SSH_CMSG_EXEC_CMD) {
365 command = packet_get_string(&dlen);
366 debug("Exec command '%.500s'", command);
378 * Any unknown messages in this phase are ignored,
379 * and a failure message is returned.
381 logit("Unknown packet type received after authentication: %d", type);
383 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
387 /* Enable compression now that we have replied if appropriate. */
388 if (enable_compression_after_reply) {
389 enable_compression_after_reply = 0;
390 packet_start_compression(compression_level);
396 * This is called to fork and execute a command when we have no tty. This
397 * will call do_child from the child, and server_loop from the parent after
398 * setting up file descriptors and such.
401 do_exec_no_pty(Session *s, const char *command)
406 int pin[2], pout[2], perr[2];
407 /* Allocate pipes for communicating with the program. */
408 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
409 packet_disconnect("Could not create pipes: %.100s",
411 #else /* USE_PIPES */
412 int inout[2], err[2];
413 /* Uses socket pairs to communicate with the program. */
414 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
415 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
416 packet_disconnect("Could not create socket pairs: %.100s",
418 #endif /* USE_PIPES */
420 fatal("do_exec_no_pty: no session");
422 session_proctitle(s);
425 if (options.use_pam && !use_privsep)
429 /* Fork the child. */
430 if ((pid = fork()) == 0) {
433 /* Child. Reinitialize the log since the pid has changed. */
434 log_init(__progname, options.log_level, options.log_facility, log_stderr);
437 * Create a new session and process group since the 4.4BSD
438 * setlogin() affects the entire process group.
441 error("setsid failed: %.100s", strerror(errno));
445 * Redirect stdin. We close the parent side of the socket
446 * pair, and make the child side the standard input.
449 if (dup2(pin[0], 0) < 0)
450 perror("dup2 stdin");
453 /* Redirect stdout. */
455 if (dup2(pout[1], 1) < 0)
456 perror("dup2 stdout");
459 /* Redirect stderr. */
461 if (dup2(perr[1], 2) < 0)
462 perror("dup2 stderr");
464 #else /* USE_PIPES */
466 * Redirect stdin, stdout, and stderr. Stdin and stdout will
467 * use the same socket, as some programs (particularly rdist)
468 * seem to depend on it.
472 if (dup2(inout[0], 0) < 0) /* stdin */
473 perror("dup2 stdin");
474 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
475 perror("dup2 stdout");
476 if (dup2(err[0], 2) < 0) /* stderr */
477 perror("dup2 stderr");
478 #endif /* USE_PIPES */
481 cray_init_job(s->pw); /* set up cray jid and tmpdir */
484 /* Do processing for the child (exec command etc). */
485 do_child(s, command);
489 signal(WJSIGNAL, cray_job_termination_handler);
493 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
496 packet_disconnect("fork failed: %.100s", strerror(errno));
498 /* Set interactive/non-interactive mode. */
499 packet_set_interactive(s->display != NULL);
501 /* We are the parent. Close the child sides of the pipes. */
507 if (s->is_subsystem) {
511 session_set_fds(s, pin[1], pout[0], perr[0]);
513 /* Enter the interactive session. */
514 server_loop(pid, pin[1], pout[0], perr[0]);
515 /* server_loop has closed pin[1], pout[0], and perr[0]. */
517 #else /* USE_PIPES */
518 /* We are the parent. Close the child sides of the socket pairs. */
523 * Clear loginmsg, since it's the child's responsibility to display
524 * it to the user, otherwise multiple sessions may accumulate
525 * multiple copies of the login messages.
527 buffer_clear(&loginmsg);
530 * Enter the interactive session. Note: server_loop must be able to
531 * handle the case that fdin and fdout are the same.
534 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
536 server_loop(pid, inout[1], inout[1], err[1]);
537 /* server_loop has closed inout[1] and err[1]. */
539 #endif /* USE_PIPES */
543 * This is called to fork and execute a command when we have a tty. This
544 * will call do_child from the child, and server_loop from the parent after
545 * setting up file descriptors, controlling tty, updating wtmp, utmp,
546 * lastlog, and other such operations.
549 do_exec_pty(Session *s, const char *command)
551 int fdout, ptyfd, ttyfd, ptymaster;
555 fatal("do_exec_pty: no session");
560 if (options.use_pam) {
561 do_pam_set_tty(s->tty);
567 /* Fork the child. */
568 if ((pid = fork()) == 0) {
571 /* Child. Reinitialize the log because the pid has changed. */
572 log_init(__progname, options.log_level, options.log_facility, log_stderr);
573 /* Close the master side of the pseudo tty. */
576 /* Make the pseudo tty our controlling tty. */
577 pty_make_controlling_tty(&ttyfd, s->tty);
579 /* Redirect stdin/stdout/stderr from the pseudo tty. */
580 if (dup2(ttyfd, 0) < 0)
581 error("dup2 stdin: %s", strerror(errno));
582 if (dup2(ttyfd, 1) < 0)
583 error("dup2 stdout: %s", strerror(errno));
584 if (dup2(ttyfd, 2) < 0)
585 error("dup2 stderr: %s", strerror(errno));
587 /* Close the extra descriptor for the pseudo tty. */
590 /* record login, etc. similar to login(1) */
592 if (!(options.use_login && command == NULL)) {
594 cray_init_job(s->pw); /* set up cray jid and tmpdir */
596 do_login(s, command);
598 # ifdef LOGIN_NEEDS_UTMPX
604 /* Do common processing for the child, such as execing the command. */
605 do_child(s, command);
609 signal(WJSIGNAL, cray_job_termination_handler);
613 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
616 packet_disconnect("fork failed: %.100s", strerror(errno));
619 /* Parent. Close the slave side of the pseudo tty. */
623 * Create another descriptor of the pty master side for use as the
624 * standard input. We could use the original descriptor, but this
625 * simplifies code in server_loop. The descriptor is bidirectional.
629 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
631 /* we keep a reference to the pty master */
632 ptymaster = dup(ptyfd);
634 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
635 s->ptymaster = ptymaster;
637 /* Enter interactive session. */
638 packet_set_interactive(1);
640 session_set_fds(s, ptyfd, fdout, -1);
642 server_loop(pid, ptyfd, fdout, -1);
643 /* server_loop _has_ closed ptyfd and fdout. */
647 #ifdef LOGIN_NEEDS_UTMPX
649 do_pre_login(Session *s)
652 struct sockaddr_storage from;
653 pid_t pid = getpid();
656 * Get IP address of client. If the connection is not a socket, let
657 * the address be 0.0.0.0.
659 memset(&from, 0, sizeof(from));
660 fromlen = sizeof(from);
661 if (packet_connection_is_on_socket()) {
662 if (getpeername(packet_get_connection_in(),
663 (struct sockaddr *) & from, &fromlen) < 0) {
664 debug("getpeername: %.100s", strerror(errno));
669 record_utmp_only(pid, s->tty, s->pw->pw_name,
670 get_remote_name_or_ip(utmp_len, options.use_dns),
671 (struct sockaddr *)&from, fromlen);
676 * This is called to fork and execute a command. If another command is
677 * to be forced, execute that instead.
680 do_exec(Session *s, const char *command)
682 if (forced_command) {
683 original_command = command;
684 command = forced_command;
685 debug("Forced command '%.900s'", command);
688 #if defined(SESSION_HOOKS)
689 if (options.session_hooks_allow &&
690 (options.session_hooks_startup_cmd ||
691 options.session_hooks_shutdown_cmd))
699 "/tmp/ssh_env_%d%d%d",
703 } while (stat(env_file, &st)==0);
704 s->authctxt->session_env_file = strdup(env_file);
709 if (options.gss_authentication) {
710 temporarily_use_uid(s->pw);
711 ssh_gssapi_storecreds();
716 #ifdef SSH_AUDIT_EVENTS
718 PRIVSEP(audit_run_command(command));
719 else if (s->ttyfd == -1) {
720 char *shell = s->pw->pw_shell;
722 if (shell[0] == '\0') /* empty shell means /bin/sh */
724 PRIVSEP(audit_run_command(shell));
729 do_exec_pty(s, command);
731 do_exec_no_pty(s, command);
733 original_command = NULL;
736 * Clear loginmsg: it's the child's responsibility to display
737 * it to the user, otherwise multiple sessions may accumulate
738 * multiple copies of the login messages.
740 buffer_clear(&loginmsg);
743 /* administrative, login(1)-like work */
745 do_login(Session *s, const char *command)
748 struct sockaddr_storage from;
749 struct passwd * pw = s->pw;
750 pid_t pid = getpid();
753 * Get IP address of client. If the connection is not a socket, let
754 * the address be 0.0.0.0.
756 memset(&from, 0, sizeof(from));
757 fromlen = sizeof(from);
758 if (packet_connection_is_on_socket()) {
759 if (getpeername(packet_get_connection_in(),
760 (struct sockaddr *) & from, &fromlen) < 0) {
761 debug("getpeername: %.100s", strerror(errno));
766 /* Record that there was a login on that tty from the remote host. */
768 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
769 get_remote_name_or_ip(utmp_len,
771 (struct sockaddr *)&from, fromlen);
775 * If password change is needed, do it now.
776 * This needs to occur before the ~/.hushlogin check.
778 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
781 s->authctxt->force_pwchange = 0;
782 /* XXX - signal [net] parent to enable forwardings */
786 if (check_quietlogin(s, command))
795 * Display the message of the day.
803 if (options.print_motd) {
804 #ifdef HAVE_LOGIN_CAP
805 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
808 f = fopen("/etc/motd", "r");
811 while (fgets(buf, sizeof(buf), f))
820 * Check for quiet login, either .hushlogin or command given.
823 check_quietlogin(Session *s, const char *command)
826 struct passwd *pw = s->pw;
829 /* Return 1 if .hushlogin exists or a command given. */
832 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
833 #ifdef HAVE_LOGIN_CAP
834 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
837 if (stat(buf, &st) >= 0)
844 * Sets the value of the given variable in the environment. If the variable
845 * already exists, its value is overriden.
848 child_set_env(char ***envp, u_int *envsizep, const char *name,
856 * If we're passed an uninitialized list, allocate a single null
857 * entry before continuing.
859 if (*envp == NULL && *envsizep == 0) {
860 *envp = xmalloc(sizeof(char *));
866 * Find the slot where the value should be stored. If the variable
867 * already exists, we reuse the slot; otherwise we append a new slot
868 * at the end of the array, expanding if necessary.
871 namelen = strlen(name);
872 for (i = 0; env[i]; i++)
873 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
876 /* Reuse the slot. */
879 /* New variable. Expand if necessary. */
881 if (i >= envsize - 1) {
883 fatal("child_set_env: too many env vars");
885 env = (*envp) = xrealloc(env, envsize * sizeof(char *));
888 /* Need to set the NULL pointer at end of array beyond the new slot. */
892 /* Allocate space and format the variable in the appropriate slot. */
893 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
894 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
898 * Reads environment variables from the given file and adds/overrides them
899 * into the environment. If the file does not exist, this does nothing.
900 * Otherwise, it must consist of empty lines, comments (line starts with '#')
901 * and assignments of the form name=value. No other forms are allowed.
904 read_environment_file(char ***env, u_int *envsize,
905 const char *filename)
912 f = fopen(filename, "r");
916 while (fgets(buf, sizeof(buf), f)) {
918 fatal("Too many lines in environment file %s", filename);
919 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
921 if (!*cp || *cp == '#' || *cp == '\n')
923 if (strchr(cp, '\n'))
924 *strchr(cp, '\n') = '\0';
925 value = strchr(cp, '=');
927 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
932 * Replace the equals sign by nul, and advance value to
937 child_set_env(env, envsize, cp, value);
943 #define SSH_SESSION_ENV_FILE "SSH_SESSION_ENV_FILE"
945 typedef enum { no_op, execute, clear_env, restore_env,
946 read_env, save_or_rm_env } session_action_t;
948 static session_action_t action_order[2][5] = {
949 { clear_env, read_env, execute, save_or_rm_env, restore_env }, /*shutdown*/
950 { execute, read_env, save_or_rm_env, no_op, no_op } /*startup */
954 void execute_session_hook(char* prog, Authctxt *authctxt,
955 int startup, int save)
957 extern char **environ;
960 char **saved_env, **tmpenv;
961 char *env_file = authctxt->session_env_file;
966 switch (action_order[startup][i])
979 authctxt->pw->pw_shell,
982 debug("executing session hook: [%s]", buf);
983 setenv(SSH_SESSION_ENV_FILE, env_file, /* overwrite = */ 1);
985 /* flusing is recommended in the popen(3) man page, to avoid
986 intermingling of output */
989 if ((fp=popen(buf, "w")) == NULL)
991 perror("Unable to run session hook");
995 debug2("session hook executed, status=%d", status);
996 unsetenv(SSH_SESSION_ENV_FILE);
1001 saved_env = environ;
1002 tmpenv = (char**) malloc(sizeof(char*));
1008 environ = saved_env;
1013 if (status==0 && stat(env_file, &st)==0)
1017 debug("reading environment from %s", env_file);
1018 while (environ[envsize++]) ;
1019 read_environment_file(&environ, &envsize, env_file);
1023 case save_or_rm_env:
1024 if (status==0 && save)
1029 debug2("saving environment to %s", env_file);
1030 if ((fp = fopen(env_file, "w")) == NULL) /* hmm: file perms? */
1032 perror("Unable to save session hook info");
1034 while (environ[envcount])
1036 fprintf(fp, "%s\n", environ[envcount++]);
1041 else if (stat(env_file, &st)==0)
1043 debug2("removing environment file %s", env_file);
1053 #ifdef HAVE_ETC_DEFAULT_LOGIN
1055 * Return named variable from specified environment, or NULL if not present.
1058 child_get_env(char **env, const char *name)
1064 for (i=0; env[i] != NULL; i++)
1065 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
1066 return(env[i] + len + 1);
1071 * Read /etc/default/login.
1072 * We pick up the PATH (or SUPATH for root) and UMASK.
1075 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
1077 char **tmpenv = NULL, *var;
1078 u_int i, tmpenvsize = 0;
1082 * We don't want to copy the whole file to the child's environment,
1083 * so we use a temporary environment and copy the variables we're
1086 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
1092 var = child_get_env(tmpenv, "SUPATH");
1094 var = child_get_env(tmpenv, "PATH");
1096 child_set_env(env, envsize, "PATH", var);
1098 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
1099 if (sscanf(var, "%5lo", &mask) == 1)
1100 umask((mode_t)mask);
1102 for (i = 0; tmpenv[i] != NULL; i++)
1106 #endif /* HAVE_ETC_DEFAULT_LOGIN */
1108 void copy_environment(char **source, char ***env, u_int *envsize)
1110 char *var_name, *var_val;
1116 for(i = 0; source[i] != NULL; i++) {
1117 var_name = xstrdup(source[i]);
1118 if ((var_val = strstr(var_name, "=")) == NULL) {
1124 debug3("Copy environment: %s=%s", var_name, var_val);
1125 child_set_env(env, envsize, var_name, var_val);
1132 do_setup_env(Session *s, const char *shell)
1136 char **env, *laddr, *path = NULL;
1137 struct passwd *pw = s->pw;
1139 /* Initialize the environment. */
1141 env = xmalloc(envsize * sizeof(char *));
1146 * The Windows environment contains some setting which are
1147 * important for a running system. They must not be dropped.
1152 p = fetch_windows_environment();
1153 copy_environment(p, &env, &envsize);
1154 free_windows_environment(p);
1159 /* Allow any GSSAPI methods that we've used to alter
1160 * the childs environment as they see fit
1162 ssh_gssapi_do_child(&env, &envsize);
1165 if (!options.use_login) {
1166 /* Set basic environment. */
1167 for (i = 0; i < s->num_env; i++)
1168 child_set_env(&env, &envsize, s->env[i].name,
1171 child_set_env(&env, &envsize, "USER", pw->pw_name);
1172 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1174 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1176 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1177 #ifdef HAVE_LOGIN_CAP
1178 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1179 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1181 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1182 #else /* HAVE_LOGIN_CAP */
1183 # ifndef HAVE_CYGWIN
1185 * There's no standard path on Windows. The path contains
1186 * important components pointing to the system directories,
1187 * needed for loading shared libraries. So the path better
1188 * remains intact here.
1190 # ifdef HAVE_ETC_DEFAULT_LOGIN
1191 read_etc_default_login(&env, &envsize, pw->pw_uid);
1192 path = child_get_env(env, "PATH");
1193 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1194 if (path == NULL || *path == '\0') {
1195 child_set_env(&env, &envsize, "PATH",
1196 s->pw->pw_uid == 0 ?
1197 SUPERUSER_PATH : _PATH_STDPATH);
1199 # endif /* HAVE_CYGWIN */
1200 #endif /* HAVE_LOGIN_CAP */
1202 snprintf(buf, sizeof buf, "%.200s/%.50s",
1203 _PATH_MAILDIR, pw->pw_name);
1204 child_set_env(&env, &envsize, "MAIL", buf);
1206 /* Normal systems set SHELL by default. */
1207 child_set_env(&env, &envsize, "SHELL", shell);
1210 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1212 #ifdef GSI /* GSI shared libs typically installed in non-system locations. */
1216 if ((cp = getenv("LD_LIBRARY_PATH")) != NULL)
1217 child_set_env(&env, &envsize, "LD_LIBRARY_PATH", cp);
1218 if ((cp = getenv("LIBPATH")) != NULL)
1219 child_set_env(&env, &envsize, "LIBPATH", cp);
1220 if ((cp = getenv("SHLIB_PATH")) != NULL)
1221 child_set_env(&env, &envsize, "SHLIB_PATH", cp);
1222 if ((cp = getenv("LD_LIBRARYN32_PATH")) != NULL)
1223 child_set_env(&env, &envsize, "LD_LIBRARYN32_PATH",cp);
1224 if ((cp = getenv("LD_LIBRARY64_PATH")) != NULL)
1225 child_set_env(&env, &envsize, "LD_LIBRARY64_PATH",cp);
1229 /* Set custom environment options from RSA authentication. */
1230 if (!options.use_login) {
1231 while (custom_environment) {
1232 struct envstring *ce = custom_environment;
1235 for (i = 0; str[i] != '=' && str[i]; i++)
1237 if (str[i] == '=') {
1239 child_set_env(&env, &envsize, str, str + i + 1);
1241 custom_environment = ce->next;
1247 /* SSH_CLIENT deprecated */
1248 snprintf(buf, sizeof buf, "%.50s %d %d",
1249 get_remote_ipaddr(), get_remote_port(), get_local_port());
1250 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1252 laddr = get_local_ipaddr(packet_get_connection_in());
1253 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1254 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1256 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1259 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1261 child_set_env(&env, &envsize, "TERM", s->term);
1263 child_set_env(&env, &envsize, "DISPLAY", s->display);
1264 if (original_command)
1265 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1269 if (cray_tmpdir[0] != '\0')
1270 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1271 #endif /* _UNICOS */
1274 * Since we clear KRB5CCNAME at startup, if it's set now then it
1275 * must have been set by a native authentication method (eg AIX or
1276 * SIA), so copy it to the child.
1281 if ((cp = getenv("KRB5CCNAME")) != NULL)
1282 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1289 if ((cp = getenv("AUTHSTATE")) != NULL)
1290 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1291 read_environment_file(&env, &envsize, "/etc/environment");
1295 if (s->authctxt->krb5_ccname)
1296 child_set_env(&env, &envsize, "KRB5CCNAME",
1297 s->authctxt->krb5_ccname);
1301 * Pull in any environment variables that may have
1304 if (options.use_pam) {
1307 p = fetch_pam_child_environment();
1308 copy_environment(p, &env, &envsize);
1309 free_pam_environment(p);
1311 p = fetch_pam_environment();
1312 copy_environment(p, &env, &envsize);
1313 free_pam_environment(p);
1315 #endif /* USE_PAM */
1317 if (auth_sock_name != NULL)
1318 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1321 /* read $HOME/.ssh/environment. */
1322 if (options.permit_user_env && !options.use_login) {
1323 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1324 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1325 read_environment_file(&env, &envsize, buf);
1328 /* dump the environment */
1329 fprintf(stderr, "Environment:\n");
1330 for (i = 0; env[i]; i++)
1331 fprintf(stderr, " %.200s\n", env[i]);
1337 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1338 * first in this order).
1341 do_rc_files(Session *s, const char *shell)
1349 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1351 /* ignore _PATH_SSH_USER_RC for subsystems */
1352 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1353 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1354 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1356 fprintf(stderr, "Running %s\n", cmd);
1357 f = popen(cmd, "w");
1360 fprintf(f, "%s %s\n", s->auth_proto,
1364 fprintf(stderr, "Could not run %s\n",
1366 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1368 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1369 _PATH_SSH_SYSTEM_RC);
1370 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1373 fprintf(f, "%s %s\n", s->auth_proto,
1377 fprintf(stderr, "Could not run %s\n",
1378 _PATH_SSH_SYSTEM_RC);
1379 } else if (do_xauth && options.xauth_location != NULL) {
1380 /* Add authority data to .Xauthority if appropriate. */
1383 "Running %.500s remove %.100s\n",
1384 options.xauth_location, s->auth_display);
1386 "%.500s add %.100s %.100s %.100s\n",
1387 options.xauth_location, s->auth_display,
1388 s->auth_proto, s->auth_data);
1390 snprintf(cmd, sizeof cmd, "%s -q -",
1391 options.xauth_location);
1392 f = popen(cmd, "w");
1394 fprintf(f, "remove %s\n",
1396 fprintf(f, "add %s %s %s\n",
1397 s->auth_display, s->auth_proto,
1401 fprintf(stderr, "Could not run %s\n",
1408 do_nologin(struct passwd *pw)
1413 #ifdef HAVE_LOGIN_CAP
1414 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1415 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1416 _PATH_NOLOGIN), "r");
1419 f = fopen(_PATH_NOLOGIN, "r");
1422 /* /etc/nologin exists. Print its contents and exit. */
1423 logit("User %.100s not allowed because %s exists",
1424 pw->pw_name, _PATH_NOLOGIN);
1425 while (fgets(buf, sizeof(buf), f))
1433 /* Set login name, uid, gid, and groups. */
1435 do_setusercontext(struct passwd *pw)
1438 if (getuid() == 0 || geteuid() == 0)
1439 #endif /* HAVE_CYGWIN */
1442 #ifdef HAVE_SETPCRED
1443 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1444 fatal("Failed to set process credentials");
1445 #endif /* HAVE_SETPCRED */
1446 #ifdef HAVE_LOGIN_CAP
1451 if (options.gss_authentication) {
1452 temporarily_use_uid(pw);
1453 ssh_gssapi_storecreds();
1458 if (options.use_pam) {
1462 # endif /* USE_PAM */
1463 if (setusercontext(lc, pw, pw->pw_uid,
1464 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1465 perror("unable to set user context");
1469 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1470 /* Sets login uid for accounting */
1471 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1472 error("setluid: %s", strerror(errno));
1473 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1475 if (setlogin(pw->pw_name) < 0)
1476 error("setlogin failed: %s", strerror(errno));
1477 if (setgid(pw->pw_gid) < 0) {
1481 /* Initialize the group list. */
1482 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1483 perror("initgroups");
1488 if (options.gss_authentication) {
1489 temporarily_use_uid(pw);
1490 ssh_gssapi_storecreds();
1496 * PAM credentials may take the form of supplementary groups.
1497 * These will have been wiped by the above initgroups() call.
1498 * Reestablish them here.
1500 if (options.use_pam) {
1504 # endif /* USE_PAM */
1505 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1506 irix_setusercontext(pw);
1507 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1511 /* Permanently switch to the desired uid. */
1512 permanently_set_uid(pw);
1519 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1520 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1524 do_pwchange(Session *s)
1527 fprintf(stderr, "WARNING: Your password has expired.\n");
1528 if (s->ttyfd != -1) {
1530 "You must change your password now and login again!\n");
1531 #ifdef PASSWD_NEEDS_USERNAME
1532 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1535 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1540 "Password change required but no TTY available.\n");
1546 launch_login(struct passwd *pw, const char *hostname)
1548 /* Launch login(1). */
1550 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1551 #ifdef xxxLOGIN_NEEDS_TERM
1552 (s->term ? s->term : "unknown"),
1553 #endif /* LOGIN_NEEDS_TERM */
1554 #ifdef LOGIN_NO_ENDOPT
1555 "-p", "-f", pw->pw_name, (char *)NULL);
1557 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1560 /* Login couldn't be executed, die. */
1567 child_close_fds(void)
1571 if (packet_get_connection_in() == packet_get_connection_out())
1572 close(packet_get_connection_in());
1574 close(packet_get_connection_in());
1575 close(packet_get_connection_out());
1578 * Close all descriptors related to channels. They will still remain
1579 * open in the parent.
1581 /* XXX better use close-on-exec? -markus */
1582 channel_close_all();
1585 * Close any extra file descriptors. Note that there may still be
1586 * descriptors left by system functions. They will be closed later.
1591 * Close any extra open file descriptors so that we don\'t have them
1592 * hanging around in clients. Note that we want to do this after
1593 * initgroups, because at least on Solaris 2.3 it leaves file
1596 for (i = 3; i < 64; i++)
1601 * Performs common processing for the child, such as setting up the
1602 * environment, closing extra file descriptors, setting the user and group
1603 * ids, and executing the command or shell.
1606 do_child(Session *s, const char *command)
1608 extern char **environ;
1611 const char *shell, *shell0, *hostname = NULL;
1612 struct passwd *pw = s->pw;
1615 /* Default place to look for aklog. */
1617 #define KPROGDIR AKLOG_PATH
1619 #define KPROGDIR "/usr/bin/aklog"
1620 #endif /* AKLOG_PATH */
1624 #endif /* AFS_KRB5 */
1626 /* remove hostkey from the child's memory */
1627 destroy_sensitive_data();
1629 /* Force a password change */
1630 if (s->authctxt->force_pwchange) {
1631 do_setusercontext(pw);
1637 /* login(1) is only called if we execute the login shell */
1638 if (options.use_login && command != NULL)
1639 options.use_login = 0;
1642 cray_setup(pw->pw_uid, pw->pw_name, command);
1643 #endif /* _UNICOS */
1646 * Login(1) does this as well, and it needs uid 0 for the "-h"
1647 * switch, so we let login(1) to this for us.
1649 if (!options.use_login) {
1651 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1652 if (!check_quietlogin(s, command))
1654 #else /* HAVE_OSF_SIA */
1656 do_setusercontext(pw);
1658 * PAM session modules in do_setusercontext may have
1659 * generated messages, so if this in an interactive
1660 * login then display them too.
1662 if (!check_quietlogin(s, command))
1664 #endif /* HAVE_OSF_SIA */
1668 if (options.use_pam && !is_pam_session_open()) {
1675 * Get the shell from the password data. An empty shell field is
1676 * legal, and means /bin/sh.
1678 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1681 * Make sure $SHELL points to the shell from the password file,
1682 * even if shell is overridden from login.conf
1684 env = do_setup_env(s, shell);
1686 #ifdef HAVE_LOGIN_CAP
1687 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1690 /* we have to stash the hostname before we close our socket. */
1691 if (options.use_login)
1692 hostname = get_remote_name_or_ip(utmp_len,
1695 * Close the connection descriptors; note that this is the child, and
1696 * the server will still have the socket open, and it is important
1697 * that we do not shutdown it. Note that the descriptors cannot be
1698 * closed before building the environment, as we call
1699 * get_remote_ipaddr there.
1704 * Must take new environment into use so that .ssh/rc,
1705 * /etc/ssh/sshrc and xauth are run in the proper environment.
1709 #if defined(KRB5) && defined(USE_AFS)
1711 * At this point, we check to see if AFS is active and if we have
1712 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1713 * if we can (and need to) extend the ticket into an AFS token. If
1714 * we don't do this, we run into potential problems if the user's
1715 * home directory is in AFS and it's not world-readable.
1718 if (options.kerberos_get_afs_token && k_hasafs() &&
1719 (s->authctxt->krb5_ctx != NULL)) {
1722 debug("Getting AFS token");
1726 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1727 krb5_afslog(s->authctxt->krb5_ctx,
1728 s->authctxt->krb5_fwd_ccache, cell, NULL);
1730 krb5_afslog_home(s->authctxt->krb5_ctx,
1731 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1737 /* User has authenticated, and if a ticket was going to be
1738 * passed we would have it. KRB5CCNAME should already be set.
1739 * Now try to get an AFS token using aklog.
1741 if (k_hasafs()) { /* Do we have AFS? */
1743 aklog_path = xstrdup(KPROGDIR);
1746 * Make sure it exists before we try to run it
1748 if (stat(aklog_path, &st) == 0) {
1749 debug("Running %s to get afs token.",aklog_path);
1752 debug("%s does not exist.",aklog_path);
1757 #endif /* AFS_KRB5 */
1759 #ifdef SESSION_HOOKS
1760 if (options.session_hooks_allow &&
1761 options.session_hooks_startup_cmd)
1763 execute_session_hook(options.session_hooks_startup_cmd,
1766 options.session_hooks_shutdown_cmd != NULL);
1770 /* Change current directory to the user\'s home directory. */
1771 if (chdir(pw->pw_dir) < 0) {
1772 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1773 pw->pw_dir, strerror(errno));
1774 #ifdef HAVE_LOGIN_CAP
1775 if (login_getcapbool(lc, "requirehome", 0))
1780 if (!options.use_login)
1781 do_rc_files(s, shell);
1783 /* restore SIGPIPE for child */
1784 signal(SIGPIPE, SIG_DFL);
1786 if (options.use_login) {
1787 launch_login(pw, hostname);
1791 /* Get the last component of the shell name. */
1792 if ((shell0 = strrchr(shell, '/')) != NULL)
1798 * If we have no command, execute the shell. In this case, the shell
1799 * name to be passed in argv[0] is preceded by '-' to indicate that
1800 * this is a login shell.
1805 /* Start the shell. Set initial character to '-'. */
1808 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1809 >= sizeof(argv0) - 1) {
1815 /* Execute the shell. */
1818 execve(shell, argv, environ);
1820 /* Executing the shell failed. */
1825 * Execute the command using the user's shell. This uses the -c
1826 * option to execute the command.
1828 argv[0] = (char *) shell0;
1830 argv[2] = (char *) command;
1832 execve(shell, argv, environ);
1841 static int did_init = 0;
1843 debug("session_new: init");
1844 for (i = 0; i < MAX_SESSIONS; i++) {
1845 sessions[i].used = 0;
1849 for (i = 0; i < MAX_SESSIONS; i++) {
1850 Session *s = &sessions[i];
1852 memset(s, 0, sizeof(*s));
1858 debug("session_new: session %d", i);
1869 for (i = 0; i < MAX_SESSIONS; i++) {
1870 Session *s = &sessions[i];
1871 debug("dump: used %d session %d %p channel %d pid %ld",
1881 session_open(Authctxt *authctxt, int chanid)
1883 Session *s = session_new();
1884 debug("session_open: channel %d", chanid);
1886 error("no more sessions");
1889 s->authctxt = authctxt;
1890 s->pw = authctxt->pw;
1891 if (s->pw == NULL || !authctxt->valid)
1892 fatal("no user for session %d", s->self);
1893 debug("session_open: session %d: link with channel %d", s->self, chanid);
1899 session_by_tty(char *tty)
1902 for (i = 0; i < MAX_SESSIONS; i++) {
1903 Session *s = &sessions[i];
1904 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1905 debug("session_by_tty: session %d tty %s", i, tty);
1909 debug("session_by_tty: unknown tty %.100s", tty);
1915 session_by_channel(int id)
1918 for (i = 0; i < MAX_SESSIONS; i++) {
1919 Session *s = &sessions[i];
1920 if (s->used && s->chanid == id) {
1921 debug("session_by_channel: session %d channel %d", i, id);
1925 debug("session_by_channel: unknown channel %d", id);
1931 session_by_pid(pid_t pid)
1934 debug("session_by_pid: pid %ld", (long)pid);
1935 for (i = 0; i < MAX_SESSIONS; i++) {
1936 Session *s = &sessions[i];
1937 if (s->used && s->pid == pid)
1940 error("session_by_pid: unknown pid %ld", (long)pid);
1946 session_window_change_req(Session *s)
1948 s->col = packet_get_int();
1949 s->row = packet_get_int();
1950 s->xpixel = packet_get_int();
1951 s->ypixel = packet_get_int();
1953 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1958 session_pty_req(Session *s)
1964 debug("Allocating a pty not permitted for this authentication.");
1967 if (s->ttyfd != -1) {
1968 packet_disconnect("Protocol error: you already have a pty.");
1972 s->term = packet_get_string(&len);
1975 s->col = packet_get_int();
1976 s->row = packet_get_int();
1978 s->row = packet_get_int();
1979 s->col = packet_get_int();
1981 s->xpixel = packet_get_int();
1982 s->ypixel = packet_get_int();
1984 if (strcmp(s->term, "") == 0) {
1989 /* Allocate a pty and open it. */
1990 debug("Allocating pty.");
1991 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1997 error("session_pty_req: session %d alloc failed", s->self);
2000 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
2002 /* for SSH1 the tty modes length is not given */
2004 n_bytes = packet_remaining();
2005 tty_parse_modes(s->ttyfd, &n_bytes);
2008 pty_setowner(s->pw, s->tty);
2010 /* Set window size from the packet. */
2011 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
2014 session_proctitle(s);
2019 session_subsystem_req(Session *s)
2024 char *cmd, *subsys = packet_get_string(&len);
2028 logit("subsystem request for %.100s", subsys);
2030 for (i = 0; i < options.num_subsystems; i++) {
2031 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
2032 cmd = options.subsystem_command[i];
2033 if (stat(cmd, &st) < 0) {
2034 error("subsystem: cannot stat %s: %s", cmd,
2038 debug("subsystem: exec() %s", cmd);
2039 s->is_subsystem = 1;
2047 logit("subsystem request for %.100s failed, subsystem not found",
2055 session_x11_req(Session *s)
2059 s->single_connection = packet_get_char();
2060 s->auth_proto = packet_get_string(NULL);
2061 s->auth_data = packet_get_string(NULL);
2062 s->screen = packet_get_int();
2065 success = session_setup_x11fwd(s);
2067 xfree(s->auth_proto);
2068 xfree(s->auth_data);
2069 s->auth_proto = NULL;
2070 s->auth_data = NULL;
2076 session_shell_req(Session *s)
2084 session_exec_req(Session *s)
2087 char *command = packet_get_string(&len);
2089 do_exec(s, command);
2095 session_break_req(Session *s)
2098 packet_get_int(); /* ignored */
2101 if (s->ttyfd == -1 ||
2102 tcsendbreak(s->ttyfd, 0) < 0)
2108 session_env_req(Session *s)
2111 u_int name_len, val_len, i;
2113 name = packet_get_string(&name_len);
2114 val = packet_get_string(&val_len);
2117 /* Don't set too many environment variables */
2118 if (s->num_env > 128) {
2119 debug2("Ignoring env request %s: too many env vars", name);
2123 for (i = 0; i < options.num_accept_env; i++) {
2124 if (match_pattern(name, options.accept_env[i])) {
2125 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2126 s->env = xrealloc(s->env, sizeof(*s->env) *
2128 s->env[s->num_env].name = name;
2129 s->env[s->num_env].val = val;
2134 debug2("Ignoring env request %s: disallowed name", name);
2143 session_auth_agent_req(Session *s)
2145 static int called = 0;
2147 if (no_agent_forwarding_flag) {
2148 debug("session_auth_agent_req: no_agent_forwarding_flag");
2155 return auth_input_request_forwarding(s->pw);
2160 session_input_channel_req(Channel *c, const char *rtype)
2165 if ((s = session_by_channel(c->self)) == NULL) {
2166 logit("session_input_channel_req: no session %d req %.100s",
2170 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2173 * a session is in LARVAL state until a shell, a command
2174 * or a subsystem is executed
2176 if (c->type == SSH_CHANNEL_LARVAL) {
2177 if (strcmp(rtype, "shell") == 0) {
2178 success = session_shell_req(s);
2179 } else if (strcmp(rtype, "exec") == 0) {
2180 success = session_exec_req(s);
2181 } else if (strcmp(rtype, "pty-req") == 0) {
2182 success = session_pty_req(s);
2183 } else if (strcmp(rtype, "x11-req") == 0) {
2184 success = session_x11_req(s);
2185 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2186 success = session_auth_agent_req(s);
2187 } else if (strcmp(rtype, "subsystem") == 0) {
2188 success = session_subsystem_req(s);
2189 } else if (strcmp(rtype, "env") == 0) {
2190 success = session_env_req(s);
2193 if (strcmp(rtype, "window-change") == 0) {
2194 success = session_window_change_req(s);
2195 } else if (strcmp(rtype, "break") == 0) {
2196 success = session_break_req(s);
2203 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2206 fatal("session_set_fds: called for proto != 2.0");
2208 * now that have a child and a pipe to the child,
2209 * we can activate our channel and register the fd's
2211 if (s->chanid == -1)
2212 fatal("no channel for session %d", s->self);
2213 channel_set_fds(s->chanid,
2215 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2217 CHAN_SES_WINDOW_DEFAULT);
2221 * Function to perform pty cleanup. Also called if we get aborted abnormally
2222 * (e.g., due to a dropped connection).
2225 session_pty_cleanup2(Session *s)
2228 error("session_pty_cleanup: no session");
2234 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2236 /* Record that the user has logged out. */
2238 record_logout(s->pid, s->tty, s->pw->pw_name);
2240 /* Release the pseudo-tty. */
2242 pty_release(s->tty);
2245 * Close the server side of the socket pairs. We must do this after
2246 * the pty cleanup, so that another process doesn't get this pty
2247 * while we're still cleaning up.
2249 if (close(s->ptymaster) < 0)
2250 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2252 /* unlink pty from session */
2257 session_pty_cleanup(Session *s)
2259 PRIVSEP(session_pty_cleanup2(s));
2265 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2280 return "SIG@openssh.com";
2284 session_exit_message(Session *s, int status)
2288 if ((c = channel_lookup(s->chanid)) == NULL)
2289 fatal("session_exit_message: session %d: no channel %d",
2290 s->self, s->chanid);
2291 debug("session_exit_message: session %d channel %d pid %ld",
2292 s->self, s->chanid, (long)s->pid);
2294 if (WIFEXITED(status)) {
2295 channel_request_start(s->chanid, "exit-status", 0);
2296 packet_put_int(WEXITSTATUS(status));
2298 } else if (WIFSIGNALED(status)) {
2299 channel_request_start(s->chanid, "exit-signal", 0);
2300 packet_put_cstring(sig2name(WTERMSIG(status)));
2302 packet_put_char(WCOREDUMP(status));
2303 #else /* WCOREDUMP */
2305 #endif /* WCOREDUMP */
2306 packet_put_cstring("");
2307 packet_put_cstring("");
2310 /* Some weird exit cause. Just exit. */
2311 packet_disconnect("wait returned status %04x.", status);
2314 /* disconnect channel */
2315 debug("session_exit_message: release channel %d", s->chanid);
2316 channel_cancel_cleanup(s->chanid);
2318 * emulate a write failure with 'chan_write_failed', nobody will be
2319 * interested in data we write.
2320 * Note that we must not call 'chan_read_failed', since there could
2321 * be some more data waiting in the pipe.
2323 if (c->ostate != CHAN_OUTPUT_CLOSED)
2324 chan_write_failed(c);
2329 session_close(Session *s)
2333 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2335 session_pty_cleanup(s);
2340 if (s->auth_display)
2341 xfree(s->auth_display);
2343 xfree(s->auth_data);
2345 xfree(s->auth_proto);
2347 for (i = 0; i < s->num_env; i++) {
2348 xfree(s->env[i].name);
2349 xfree(s->env[i].val);
2353 session_proctitle(s);
2357 session_close_by_pid(pid_t pid, int status)
2359 Session *s = session_by_pid(pid);
2361 debug("session_close_by_pid: no session for pid %ld",
2365 if (s->chanid != -1)
2366 session_exit_message(s, status);
2371 * this is called when a channel dies before
2372 * the session 'child' itself dies
2375 session_close_by_channel(int id, void *arg)
2377 Session *s = session_by_channel(id);
2379 debug("session_close_by_channel: no session for id %d", id);
2382 debug("session_close_by_channel: channel %d child %ld",
2385 debug("session_close_by_channel: channel %d: has child", id);
2387 * delay detach of session, but release pty, since
2388 * the fd's to the child are already closed
2391 session_pty_cleanup(s);
2394 /* detach by removing callback */
2395 channel_cancel_cleanup(s->chanid);
2401 session_destroy_all(void (*closefunc)(Session *))
2404 for (i = 0; i < MAX_SESSIONS; i++) {
2405 Session *s = &sessions[i];
2407 if (closefunc != NULL)
2416 session_tty_list(void)
2418 static char buf[1024];
2423 for (i = 0; i < MAX_SESSIONS; i++) {
2424 Session *s = &sessions[i];
2425 if (s->used && s->ttyfd != -1) {
2427 if (strncmp(s->tty, "/dev/", 5) != 0) {
2428 cp = strrchr(s->tty, '/');
2429 cp = (cp == NULL) ? s->tty : cp + 1;
2434 strlcat(buf, ",", sizeof buf);
2435 strlcat(buf, cp, sizeof buf);
2439 strlcpy(buf, "notty", sizeof buf);
2444 session_proctitle(Session *s)
2447 error("no user for session %d", s->self);
2449 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2453 session_setup_x11fwd(Session *s)
2456 char display[512], auth_display[512];
2457 char hostname[MAXHOSTNAMELEN];
2459 if (no_x11_forwarding_flag) {
2460 packet_send_debug("X11 forwarding disabled in user configuration file.");
2463 if (!options.x11_forwarding) {
2464 debug("X11 forwarding disabled in server configuration file.");
2467 if (!options.xauth_location ||
2468 (stat(options.xauth_location, &st) == -1)) {
2469 packet_send_debug("No xauth program; cannot forward with spoofing.");
2472 if (options.use_login) {
2473 packet_send_debug("X11 forwarding disabled; "
2474 "not compatible with UseLogin=yes.");
2477 if (s->display != NULL) {
2478 debug("X11 display already set.");
2481 if (x11_create_display_inet(options.x11_display_offset,
2482 options.x11_use_localhost, s->single_connection,
2483 &s->display_number) == -1) {
2484 debug("x11_create_display_inet failed.");
2488 /* Set up a suitable value for the DISPLAY variable. */
2489 if (gethostname(hostname, sizeof(hostname)) < 0)
2490 fatal("gethostname: %.100s", strerror(errno));
2492 * auth_display must be used as the displayname when the
2493 * authorization entry is added with xauth(1). This will be
2494 * different than the DISPLAY string for localhost displays.
2496 if (options.x11_use_localhost) {
2497 snprintf(display, sizeof display, "localhost:%u.%u",
2498 s->display_number, s->screen);
2499 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2500 s->display_number, s->screen);
2501 s->display = xstrdup(display);
2502 s->auth_display = xstrdup(auth_display);
2504 #ifdef IPADDR_IN_DISPLAY
2506 struct in_addr my_addr;
2508 he = gethostbyname(hostname);
2510 error("Can't get IP address for X11 DISPLAY.");
2511 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2514 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2515 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2516 s->display_number, s->screen);
2518 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2519 s->display_number, s->screen);
2521 s->display = xstrdup(display);
2522 s->auth_display = xstrdup(display);
2529 do_authenticated2(Authctxt *authctxt)
2531 server_loop2(authctxt);
2535 do_cleanup(Authctxt *authctxt)
2537 static int called = 0;
2539 debug("do_cleanup");
2541 /* no cleanup if we're in the child for login shell */
2545 /* avoid double cleanup */
2550 if (authctxt == NULL)
2553 if (options.kerberos_ticket_cleanup &&
2555 krb5_cleanup_proc(authctxt);
2559 if (compat20 && options.gss_cleanup_creds)
2560 ssh_gssapi_cleanup_creds();
2564 if (options.use_pam) {
2566 sshpam_thread_cleanup();
2570 /* remove agent socket */
2571 auth_sock_cleanup_proc(authctxt->pw);
2574 * Cleanup ptys/utmp only if privsep is disabled,
2575 * or if running in monitor.
2577 if (!use_privsep || mm_is_monitor())
2578 session_destroy_all(session_pty_cleanup2);