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.172 2004/01/30 09:48:57 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\n", (char *)buffer_ptr(&loginmsg));
207 buffer_clear(&loginmsg);
213 do_authenticated(Authctxt *authctxt)
215 setproctitle("%s", authctxt->pw->pw_name);
218 * Cancel the alarm we set to limit the time taken for
222 if (startup_pipe != -1) {
226 /* setup the channel layer */
227 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
228 channel_permit_all_opens();
231 do_authenticated2(authctxt);
233 do_authenticated1(authctxt);
236 if (options.session_hooks_allow &&
237 options.session_hooks_shutdown_cmd)
239 execute_session_hook(options.session_hooks_shutdown_cmd,
241 /* startup = */ 0, /* save = */ 0);
243 if (authctxt->session_env_file)
245 free(authctxt->session_env_file);
250 do_cleanup(authctxt);
254 * Prepares for an interactive session. This is called after the user has
255 * been successfully authenticated. During this message exchange, pseudo
256 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
257 * are requested, etc.
260 do_authenticated1(Authctxt *authctxt)
264 int success, type, screen_flag;
265 int enable_compression_after_reply = 0;
266 u_int proto_len, data_len, dlen, compression_level = 0;
269 s->authctxt = authctxt;
270 s->pw = authctxt->pw;
273 * We stay in this loop until the client requests to execute a shell
279 /* Get a packet from the client. */
280 type = packet_read();
282 /* Process the packet. */
284 case SSH_CMSG_REQUEST_COMPRESSION:
285 compression_level = packet_get_int();
287 if (compression_level < 1 || compression_level > 9) {
288 packet_send_debug("Received illegal compression level %d.",
292 if (!options.compression) {
293 debug2("compression disabled");
296 /* Enable compression after we have responded with SUCCESS. */
297 enable_compression_after_reply = 1;
301 case SSH_CMSG_REQUEST_PTY:
302 success = session_pty_req(s);
305 case SSH_CMSG_X11_REQUEST_FORWARDING:
306 s->auth_proto = packet_get_string(&proto_len);
307 s->auth_data = packet_get_string(&data_len);
309 screen_flag = packet_get_protocol_flags() &
310 SSH_PROTOFLAG_SCREEN_NUMBER;
311 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
313 if (packet_remaining() == 4) {
315 debug2("Buggy client: "
316 "X11 screen flag missing");
317 s->screen = packet_get_int();
322 success = session_setup_x11fwd(s);
324 xfree(s->auth_proto);
326 s->auth_proto = NULL;
331 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
332 if (no_agent_forwarding_flag || compat13) {
333 debug("Authentication agent forwarding not permitted for this authentication.");
336 debug("Received authentication agent forwarding request.");
337 success = auth_input_request_forwarding(s->pw);
340 case SSH_CMSG_PORT_FORWARD_REQUEST:
341 if (no_port_forwarding_flag) {
342 debug("Port forwarding not permitted for this authentication.");
345 if (!options.allow_tcp_forwarding) {
346 debug("Port forwarding not permitted.");
349 debug("Received TCP/IP port forwarding request.");
350 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
354 case SSH_CMSG_MAX_PACKET_SIZE:
355 if (packet_set_maxsize(packet_get_int()) > 0)
359 case SSH_CMSG_EXEC_SHELL:
360 case SSH_CMSG_EXEC_CMD:
361 if (type == SSH_CMSG_EXEC_CMD) {
362 command = packet_get_string(&dlen);
363 debug("Exec command '%.500s'", command);
375 * Any unknown messages in this phase are ignored,
376 * and a failure message is returned.
378 logit("Unknown packet type received after authentication: %d", type);
380 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
384 /* Enable compression now that we have replied if appropriate. */
385 if (enable_compression_after_reply) {
386 enable_compression_after_reply = 0;
387 packet_start_compression(compression_level);
393 * This is called to fork and execute a command when we have no tty. This
394 * will call do_child from the child, and server_loop from the parent after
395 * setting up file descriptors and such.
398 do_exec_no_pty(Session *s, const char *command)
403 int pin[2], pout[2], perr[2];
404 /* Allocate pipes for communicating with the program. */
405 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
406 packet_disconnect("Could not create pipes: %.100s",
408 #else /* USE_PIPES */
409 int inout[2], err[2];
410 /* Uses socket pairs to communicate with the program. */
411 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
412 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
413 packet_disconnect("Could not create socket pairs: %.100s",
415 #endif /* USE_PIPES */
417 fatal("do_exec_no_pty: no session");
419 session_proctitle(s);
422 if (options.use_pam && !use_privsep)
426 /* Fork the child. */
427 if ((pid = fork()) == 0) {
430 /* Child. Reinitialize the log since the pid has changed. */
431 log_init(__progname, options.log_level, options.log_facility, log_stderr);
434 * Create a new session and process group since the 4.4BSD
435 * setlogin() affects the entire process group.
438 error("setsid failed: %.100s", strerror(errno));
442 * Redirect stdin. We close the parent side of the socket
443 * pair, and make the child side the standard input.
446 if (dup2(pin[0], 0) < 0)
447 perror("dup2 stdin");
450 /* Redirect stdout. */
452 if (dup2(pout[1], 1) < 0)
453 perror("dup2 stdout");
456 /* Redirect stderr. */
458 if (dup2(perr[1], 2) < 0)
459 perror("dup2 stderr");
461 #else /* USE_PIPES */
463 * Redirect stdin, stdout, and stderr. Stdin and stdout will
464 * use the same socket, as some programs (particularly rdist)
465 * seem to depend on it.
469 if (dup2(inout[0], 0) < 0) /* stdin */
470 perror("dup2 stdin");
471 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
472 perror("dup2 stdout");
473 if (dup2(err[0], 2) < 0) /* stderr */
474 perror("dup2 stderr");
475 #endif /* USE_PIPES */
478 cray_init_job(s->pw); /* set up cray jid and tmpdir */
481 /* Do processing for the child (exec command etc). */
482 do_child(s, command);
486 signal(WJSIGNAL, cray_job_termination_handler);
490 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
493 packet_disconnect("fork failed: %.100s", strerror(errno));
495 /* Set interactive/non-interactive mode. */
496 packet_set_interactive(s->display != NULL);
498 /* We are the parent. Close the child sides of the pipes. */
504 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
506 /* Enter the interactive session. */
507 server_loop(pid, pin[1], pout[0], perr[0]);
508 /* server_loop has closed pin[1], pout[0], and perr[0]. */
510 #else /* USE_PIPES */
511 /* We are the parent. Close the child sides of the socket pairs. */
516 * Clear loginmsg, since it's the child's responsibility to display
517 * it to the user, otherwise multiple sessions may accumulate
518 * multiple copies of the login messages.
520 buffer_clear(&loginmsg);
523 * Enter the interactive session. Note: server_loop must be able to
524 * handle the case that fdin and fdout are the same.
527 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
529 server_loop(pid, inout[1], inout[1], err[1]);
530 /* server_loop has closed inout[1] and err[1]. */
532 #endif /* USE_PIPES */
536 * This is called to fork and execute a command when we have a tty. This
537 * will call do_child from the child, and server_loop from the parent after
538 * setting up file descriptors, controlling tty, updating wtmp, utmp,
539 * lastlog, and other such operations.
542 do_exec_pty(Session *s, const char *command)
544 int fdout, ptyfd, ttyfd, ptymaster;
548 fatal("do_exec_pty: no session");
553 if (options.use_pam) {
554 do_pam_set_tty(s->tty);
560 /* Fork the child. */
561 if ((pid = fork()) == 0) {
564 /* Child. Reinitialize the log because the pid has changed. */
565 log_init(__progname, options.log_level, options.log_facility, log_stderr);
566 /* Close the master side of the pseudo tty. */
569 /* Make the pseudo tty our controlling tty. */
570 pty_make_controlling_tty(&ttyfd, s->tty);
572 /* Redirect stdin/stdout/stderr from the pseudo tty. */
573 if (dup2(ttyfd, 0) < 0)
574 error("dup2 stdin: %s", strerror(errno));
575 if (dup2(ttyfd, 1) < 0)
576 error("dup2 stdout: %s", strerror(errno));
577 if (dup2(ttyfd, 2) < 0)
578 error("dup2 stderr: %s", strerror(errno));
580 /* Close the extra descriptor for the pseudo tty. */
583 /* record login, etc. similar to login(1) */
585 if (!(options.use_login && command == NULL)) {
587 cray_init_job(s->pw); /* set up cray jid and tmpdir */
589 do_login(s, command);
591 # ifdef LOGIN_NEEDS_UTMPX
597 /* Do common processing for the child, such as execing the command. */
598 do_child(s, command);
602 signal(WJSIGNAL, cray_job_termination_handler);
606 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
609 packet_disconnect("fork failed: %.100s", strerror(errno));
612 /* Parent. Close the slave side of the pseudo tty. */
616 * Create another descriptor of the pty master side for use as the
617 * standard input. We could use the original descriptor, but this
618 * simplifies code in server_loop. The descriptor is bidirectional.
622 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
624 /* we keep a reference to the pty master */
625 ptymaster = dup(ptyfd);
627 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
628 s->ptymaster = ptymaster;
630 /* Enter interactive session. */
631 packet_set_interactive(1);
633 session_set_fds(s, ptyfd, fdout, -1);
635 server_loop(pid, ptyfd, fdout, -1);
636 /* server_loop _has_ closed ptyfd and fdout. */
640 #ifdef LOGIN_NEEDS_UTMPX
642 do_pre_login(Session *s)
645 struct sockaddr_storage from;
646 pid_t pid = getpid();
649 * Get IP address of client. If the connection is not a socket, let
650 * the address be 0.0.0.0.
652 memset(&from, 0, sizeof(from));
653 fromlen = sizeof(from);
654 if (packet_connection_is_on_socket()) {
655 if (getpeername(packet_get_connection_in(),
656 (struct sockaddr *) & from, &fromlen) < 0) {
657 debug("getpeername: %.100s", strerror(errno));
662 record_utmp_only(pid, s->tty, s->pw->pw_name,
663 get_remote_name_or_ip(utmp_len, options.use_dns),
664 (struct sockaddr *)&from, fromlen);
669 * This is called to fork and execute a command. If another command is
670 * to be forced, execute that instead.
673 do_exec(Session *s, const char *command)
675 if (forced_command) {
676 original_command = command;
677 command = forced_command;
678 debug("Forced command '%.900s'", command);
681 #if defined(SESSION_HOOKS)
682 if (options.session_hooks_allow &&
683 (options.session_hooks_startup_cmd ||
684 options.session_hooks_shutdown_cmd))
692 "/tmp/ssh_env_%d%d%d",
696 } while (stat(env_file, &st)==0);
697 s->authctxt->session_env_file = strdup(env_file);
702 if (options.gss_authentication) {
703 temporarily_use_uid(s->pw);
704 ssh_gssapi_storecreds();
710 do_exec_pty(s, command);
712 do_exec_no_pty(s, command);
714 original_command = NULL;
718 /* administrative, login(1)-like work */
720 do_login(Session *s, const char *command)
724 struct sockaddr_storage from;
725 struct passwd * pw = s->pw;
726 pid_t pid = getpid();
729 * Get IP address of client. If the connection is not a socket, let
730 * the address be 0.0.0.0.
732 memset(&from, 0, sizeof(from));
733 fromlen = sizeof(from);
734 if (packet_connection_is_on_socket()) {
735 if (getpeername(packet_get_connection_in(),
736 (struct sockaddr *) & from, &fromlen) < 0) {
737 debug("getpeername: %.100s", strerror(errno));
742 /* Record that there was a login on that tty from the remote host. */
744 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
745 get_remote_name_or_ip(utmp_len,
747 (struct sockaddr *)&from, fromlen);
751 * If password change is needed, do it now.
752 * This needs to occur before the ~/.hushlogin check.
754 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
757 s->authctxt->force_pwchange = 0;
758 /* XXX - signal [net] parent to enable forwardings */
762 if (check_quietlogin(s, command))
767 #ifndef NO_SSH_LASTLOG
768 if (options.print_lastlog && s->last_login_time != 0) {
769 time_string = ctime(&s->last_login_time);
770 if (strchr(time_string, '\n'))
771 *strchr(time_string, '\n') = 0;
772 if (strcmp(s->hostname, "") == 0)
773 printf("Last login: %s\r\n", time_string);
775 printf("Last login: %s from %s\r\n", time_string,
778 #endif /* NO_SSH_LASTLOG */
784 * Display the message of the day.
792 if (options.print_motd) {
793 #ifdef HAVE_LOGIN_CAP
794 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
797 f = fopen("/etc/motd", "r");
800 while (fgets(buf, sizeof(buf), f))
809 * Check for quiet login, either .hushlogin or command given.
812 check_quietlogin(Session *s, const char *command)
815 struct passwd *pw = s->pw;
818 /* Return 1 if .hushlogin exists or a command given. */
821 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
822 #ifdef HAVE_LOGIN_CAP
823 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
826 if (stat(buf, &st) >= 0)
833 * Sets the value of the given variable in the environment. If the variable
834 * already exists, its value is overriden.
837 child_set_env(char ***envp, u_int *envsizep, const char *name,
845 * If we're passed an uninitialized list, allocate a single null
846 * entry before continuing.
848 if (*envp == NULL && *envsizep == 0) {
849 *envp = xmalloc(sizeof(char *));
855 * Find the slot where the value should be stored. If the variable
856 * already exists, we reuse the slot; otherwise we append a new slot
857 * at the end of the array, expanding if necessary.
860 namelen = strlen(name);
861 for (i = 0; env[i]; i++)
862 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
865 /* Reuse the slot. */
868 /* New variable. Expand if necessary. */
870 if (i >= envsize - 1) {
872 fatal("child_set_env: too many env vars");
874 env = (*envp) = xrealloc(env, envsize * sizeof(char *));
877 /* Need to set the NULL pointer at end of array beyond the new slot. */
881 /* Allocate space and format the variable in the appropriate slot. */
882 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
883 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
887 * Reads environment variables from the given file and adds/overrides them
888 * into the environment. If the file does not exist, this does nothing.
889 * Otherwise, it must consist of empty lines, comments (line starts with '#')
890 * and assignments of the form name=value. No other forms are allowed.
893 read_environment_file(char ***env, u_int *envsize,
894 const char *filename)
901 f = fopen(filename, "r");
905 while (fgets(buf, sizeof(buf), f)) {
907 fatal("Too many lines in environment file %s", filename);
908 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
910 if (!*cp || *cp == '#' || *cp == '\n')
912 if (strchr(cp, '\n'))
913 *strchr(cp, '\n') = '\0';
914 value = strchr(cp, '=');
916 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
921 * Replace the equals sign by nul, and advance value to
926 child_set_env(env, envsize, cp, value);
932 #define SSH_SESSION_ENV_FILE "SSH_SESSION_ENV_FILE"
934 typedef enum { no_op, execute, clear_env, restore_env,
935 read_env, save_or_rm_env } session_action_t;
937 static session_action_t action_order[2][5] = {
938 { clear_env, read_env, execute, save_or_rm_env, restore_env }, /*shutdown*/
939 { execute, read_env, save_or_rm_env, no_op, no_op } /*startup */
943 void execute_session_hook(char* prog, Authctxt *authctxt,
944 int startup, int save)
946 extern char **environ;
949 char **saved_env, **tmpenv;
950 char *env_file = authctxt->session_env_file;
955 switch (action_order[startup][i])
968 authctxt->pw->pw_shell,
971 debug("executing session hook: [%s]", buf);
972 setenv(SSH_SESSION_ENV_FILE, env_file, /* overwrite = */ 1);
974 /* flusing is recommended in the popen(3) man page, to avoid
975 intermingling of output */
978 if ((fp=popen(buf, "w")) == NULL)
980 perror("Unable to run session hook");
984 debug2("session hook executed, status=%d", status);
985 unsetenv(SSH_SESSION_ENV_FILE);
991 tmpenv = (char**) malloc(sizeof(char*));
1002 if (status==0 && stat(env_file, &st)==0)
1006 debug("reading environment from %s", env_file);
1007 while (environ[envsize++]) ;
1008 read_environment_file(&environ, &envsize, env_file);
1012 case save_or_rm_env:
1013 if (status==0 && save)
1018 debug2("saving environment to %s", env_file);
1019 if ((fp = fopen(env_file, "w")) == NULL) /* hmm: file perms? */
1021 perror("Unable to save session hook info");
1023 while (environ[envcount])
1025 fprintf(fp, "%s\n", environ[envcount++]);
1030 else if (stat(env_file, &st)==0)
1032 debug2("removing environment file %s", env_file);
1042 #ifdef HAVE_ETC_DEFAULT_LOGIN
1044 * Return named variable from specified environment, or NULL if not present.
1047 child_get_env(char **env, const char *name)
1053 for (i=0; env[i] != NULL; i++)
1054 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
1055 return(env[i] + len + 1);
1060 * Read /etc/default/login.
1061 * We pick up the PATH (or SUPATH for root) and UMASK.
1064 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
1066 char **tmpenv = NULL, *var;
1067 u_int i, tmpenvsize = 0;
1071 * We don't want to copy the whole file to the child's environment,
1072 * so we use a temporary environment and copy the variables we're
1075 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
1081 var = child_get_env(tmpenv, "SUPATH");
1083 var = child_get_env(tmpenv, "PATH");
1085 child_set_env(env, envsize, "PATH", var);
1087 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
1088 if (sscanf(var, "%5lo", &mask) == 1)
1089 umask((mode_t)mask);
1091 for (i = 0; tmpenv[i] != NULL; i++)
1095 #endif /* HAVE_ETC_DEFAULT_LOGIN */
1097 void copy_environment(char **source, char ***env, u_int *envsize)
1099 char *var_name, *var_val;
1105 for(i = 0; source[i] != NULL; i++) {
1106 var_name = xstrdup(source[i]);
1107 if ((var_val = strstr(var_name, "=")) == NULL) {
1113 debug3("Copy environment: %s=%s", var_name, var_val);
1114 child_set_env(env, envsize, var_name, var_val);
1121 do_setup_env(Session *s, const char *shell)
1125 char **env, *laddr, *path = NULL;
1126 struct passwd *pw = s->pw;
1128 /* Initialize the environment. */
1130 env = xmalloc(envsize * sizeof(char *));
1135 * The Windows environment contains some setting which are
1136 * important for a running system. They must not be dropped.
1138 copy_environment(environ, &env, &envsize);
1142 /* Allow any GSSAPI methods that we've used to alter
1143 * the childs environment as they see fit
1145 ssh_gssapi_do_child(&env, &envsize);
1148 if (!options.use_login) {
1149 /* Set basic environment. */
1150 child_set_env(&env, &envsize, "USER", pw->pw_name);
1151 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1153 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1155 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1156 #ifdef HAVE_LOGIN_CAP
1157 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1158 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1160 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1161 #else /* HAVE_LOGIN_CAP */
1162 # ifndef HAVE_CYGWIN
1164 * There's no standard path on Windows. The path contains
1165 * important components pointing to the system directories,
1166 * needed for loading shared libraries. So the path better
1167 * remains intact here.
1169 # ifdef HAVE_ETC_DEFAULT_LOGIN
1170 read_etc_default_login(&env, &envsize, pw->pw_uid);
1171 path = child_get_env(env, "PATH");
1172 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1173 if (path == NULL || *path == '\0') {
1174 child_set_env(&env, &envsize, "PATH",
1175 s->pw->pw_uid == 0 ?
1176 SUPERUSER_PATH : _PATH_STDPATH);
1178 # endif /* HAVE_CYGWIN */
1179 #endif /* HAVE_LOGIN_CAP */
1181 snprintf(buf, sizeof buf, "%.200s/%.50s",
1182 _PATH_MAILDIR, pw->pw_name);
1183 child_set_env(&env, &envsize, "MAIL", buf);
1185 /* Normal systems set SHELL by default. */
1186 child_set_env(&env, &envsize, "SHELL", shell);
1189 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1191 #ifdef GSI /* GSI shared libs typically installed in non-system locations. */
1195 if ((cp = getenv("LD_LIBRARY_PATH")) != NULL)
1196 child_set_env(&env, &envsize, "LD_LIBRARY_PATH", cp);
1197 if ((cp = getenv("LIBPATH")) != NULL)
1198 child_set_env(&env, &envsize, "LIBPATH", cp);
1199 if ((cp = getenv("SHLIB_PATH")) != NULL)
1200 child_set_env(&env, &envsize, "SHLIB_PATH", cp);
1201 if ((cp = getenv("LD_LIBRARYN32_PATH")) != NULL)
1202 child_set_env(&env, &envsize, "LD_LIBRARYN32_PATH",cp);
1203 if ((cp = getenv("LD_LIBRARY64_PATH")) != NULL)
1204 child_set_env(&env, &envsize, "LD_LIBRARY64_PATH",cp);
1208 /* Set custom environment options from RSA authentication. */
1209 if (!options.use_login) {
1210 while (custom_environment) {
1211 struct envstring *ce = custom_environment;
1214 for (i = 0; str[i] != '=' && str[i]; i++)
1216 if (str[i] == '=') {
1218 child_set_env(&env, &envsize, str, str + i + 1);
1220 custom_environment = ce->next;
1226 /* SSH_CLIENT deprecated */
1227 snprintf(buf, sizeof buf, "%.50s %d %d",
1228 get_remote_ipaddr(), get_remote_port(), get_local_port());
1229 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1231 laddr = get_local_ipaddr(packet_get_connection_in());
1232 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1233 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1235 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1238 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1240 child_set_env(&env, &envsize, "TERM", s->term);
1242 child_set_env(&env, &envsize, "DISPLAY", s->display);
1243 if (original_command)
1244 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1248 if (cray_tmpdir[0] != '\0')
1249 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1250 #endif /* _UNICOS */
1256 if ((cp = getenv("AUTHSTATE")) != NULL)
1257 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1258 if ((cp = getenv("KRB5CCNAME")) != NULL)
1259 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1260 read_environment_file(&env, &envsize, "/etc/environment");
1264 if (s->authctxt->krb5_ccname)
1265 child_set_env(&env, &envsize, "KRB5CCNAME",
1266 s->authctxt->krb5_ccname);
1270 * Pull in any environment variables that may have
1273 if (options.use_pam) {
1276 p = fetch_pam_child_environment();
1277 copy_environment(p, &env, &envsize);
1278 free_pam_environment(p);
1280 p = fetch_pam_environment();
1281 copy_environment(p, &env, &envsize);
1282 free_pam_environment(p);
1284 #endif /* USE_PAM */
1286 if (auth_sock_name != NULL)
1287 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1290 /* read $HOME/.ssh/environment. */
1291 if (options.permit_user_env && !options.use_login) {
1292 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1293 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1294 read_environment_file(&env, &envsize, buf);
1297 /* dump the environment */
1298 fprintf(stderr, "Environment:\n");
1299 for (i = 0; env[i]; i++)
1300 fprintf(stderr, " %.200s\n", env[i]);
1306 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1307 * first in this order).
1310 do_rc_files(Session *s, const char *shell)
1318 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1320 /* ignore _PATH_SSH_USER_RC for subsystems */
1321 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1322 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1323 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1325 fprintf(stderr, "Running %s\n", cmd);
1326 f = popen(cmd, "w");
1329 fprintf(f, "%s %s\n", s->auth_proto,
1333 fprintf(stderr, "Could not run %s\n",
1335 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1337 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1338 _PATH_SSH_SYSTEM_RC);
1339 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1342 fprintf(f, "%s %s\n", s->auth_proto,
1346 fprintf(stderr, "Could not run %s\n",
1347 _PATH_SSH_SYSTEM_RC);
1348 } else if (do_xauth && options.xauth_location != NULL) {
1349 /* Add authority data to .Xauthority if appropriate. */
1352 "Running %.500s remove %.100s\n",
1353 options.xauth_location, s->auth_display);
1355 "%.500s add %.100s %.100s %.100s\n",
1356 options.xauth_location, s->auth_display,
1357 s->auth_proto, s->auth_data);
1359 snprintf(cmd, sizeof cmd, "%s -q -",
1360 options.xauth_location);
1361 f = popen(cmd, "w");
1363 fprintf(f, "remove %s\n",
1365 fprintf(f, "add %s %s %s\n",
1366 s->auth_display, s->auth_proto,
1370 fprintf(stderr, "Could not run %s\n",
1377 do_nologin(struct passwd *pw)
1382 #ifdef HAVE_LOGIN_CAP
1383 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1384 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1385 _PATH_NOLOGIN), "r");
1388 f = fopen(_PATH_NOLOGIN, "r");
1391 /* /etc/nologin exists. Print its contents and exit. */
1392 logit("User %.100s not allowed because %s exists",
1393 pw->pw_name, _PATH_NOLOGIN);
1394 while (fgets(buf, sizeof(buf), f))
1402 /* Set login name, uid, gid, and groups. */
1404 do_setusercontext(struct passwd *pw)
1407 if (getuid() == 0 || geteuid() == 0)
1408 #endif /* HAVE_CYGWIN */
1411 #ifdef HAVE_SETPCRED
1412 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1413 fatal("Failed to set process credentials");
1414 #endif /* HAVE_SETPCRED */
1415 #ifdef HAVE_LOGIN_CAP
1420 if (options.use_pam) {
1424 # endif /* USE_PAM */
1425 if (setusercontext(lc, pw, pw->pw_uid,
1426 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1427 perror("unable to set user context");
1431 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1432 /* Sets login uid for accounting */
1433 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1434 error("setluid: %s", strerror(errno));
1435 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1437 if (setlogin(pw->pw_name) < 0)
1438 error("setlogin failed: %s", strerror(errno));
1439 if (setgid(pw->pw_gid) < 0) {
1443 /* Initialize the group list. */
1444 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1445 perror("initgroups");
1451 * PAM credentials may take the form of supplementary groups.
1452 * These will have been wiped by the above initgroups() call.
1453 * Reestablish them here.
1455 if (options.use_pam) {
1459 # endif /* USE_PAM */
1460 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1461 irix_setusercontext(pw);
1462 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1466 /* Permanently switch to the desired uid. */
1467 permanently_set_uid(pw);
1474 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1475 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1479 do_pwchange(Session *s)
1481 fprintf(stderr, "WARNING: Your password has expired.\n");
1482 if (s->ttyfd != -1) {
1484 "You must change your password now and login again!\n");
1485 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1489 "Password change required but no TTY available.\n");
1495 launch_login(struct passwd *pw, const char *hostname)
1497 /* Launch login(1). */
1499 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1500 #ifdef xxxLOGIN_NEEDS_TERM
1501 (s->term ? s->term : "unknown"),
1502 #endif /* LOGIN_NEEDS_TERM */
1503 #ifdef LOGIN_NO_ENDOPT
1504 "-p", "-f", pw->pw_name, (char *)NULL);
1506 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1509 /* Login couldn't be executed, die. */
1516 child_close_fds(void)
1520 if (packet_get_connection_in() == packet_get_connection_out())
1521 close(packet_get_connection_in());
1523 close(packet_get_connection_in());
1524 close(packet_get_connection_out());
1527 * Close all descriptors related to channels. They will still remain
1528 * open in the parent.
1530 /* XXX better use close-on-exec? -markus */
1531 channel_close_all();
1534 * Close any extra file descriptors. Note that there may still be
1535 * descriptors left by system functions. They will be closed later.
1540 * Close any extra open file descriptors so that we don\'t have them
1541 * hanging around in clients. Note that we want to do this after
1542 * initgroups, because at least on Solaris 2.3 it leaves file
1545 for (i = 3; i < 64; i++)
1550 * Performs common processing for the child, such as setting up the
1551 * environment, closing extra file descriptors, setting the user and group
1552 * ids, and executing the command or shell.
1555 do_child(Session *s, const char *command)
1557 extern char **environ;
1560 const char *shell, *shell0, *hostname = NULL;
1561 struct passwd *pw = s->pw;
1564 /* Default place to look for aklog. */
1566 #define KPROGDIR AKLOG_PATH
1568 #define KPROGDIR "/usr/bin/aklog"
1569 #endif /* AKLOG_PATH */
1573 #endif /* AFS_KRB5 */
1575 /* remove hostkey from the child's memory */
1576 destroy_sensitive_data();
1578 /* Force a password change */
1579 if (s->authctxt->force_pwchange) {
1580 do_setusercontext(pw);
1586 /* login(1) is only called if we execute the login shell */
1587 if (options.use_login && command != NULL)
1588 options.use_login = 0;
1591 cray_setup(pw->pw_uid, pw->pw_name, command);
1592 #endif /* _UNICOS */
1595 * Login(1) does this as well, and it needs uid 0 for the "-h"
1596 * switch, so we let login(1) to this for us.
1598 if (!options.use_login) {
1600 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1601 if (!check_quietlogin(s, command))
1603 #else /* HAVE_OSF_SIA */
1605 do_setusercontext(pw);
1606 #endif /* HAVE_OSF_SIA */
1610 * Get the shell from the password data. An empty shell field is
1611 * legal, and means /bin/sh.
1613 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1616 * Make sure $SHELL points to the shell from the password file,
1617 * even if shell is overridden from login.conf
1619 env = do_setup_env(s, shell);
1621 #ifdef HAVE_LOGIN_CAP
1622 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1625 /* we have to stash the hostname before we close our socket. */
1626 if (options.use_login)
1627 hostname = get_remote_name_or_ip(utmp_len,
1630 * Close the connection descriptors; note that this is the child, and
1631 * the server will still have the socket open, and it is important
1632 * that we do not shutdown it. Note that the descriptors cannot be
1633 * closed before building the environment, as we call
1634 * get_remote_ipaddr there.
1639 * Must take new environment into use so that .ssh/rc,
1640 * /etc/ssh/sshrc and xauth are run in the proper environment.
1644 #if defined(KRB5) && defined(USE_AFS)
1646 * At this point, we check to see if AFS is active and if we have
1647 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1648 * if we can (and need to) extend the ticket into an AFS token. If
1649 * we don't do this, we run into potential problems if the user's
1650 * home directory is in AFS and it's not world-readable.
1653 if (options.kerberos_get_afs_token && k_hasafs() &&
1654 (s->authctxt->krb5_ctx != NULL)) {
1657 debug("Getting AFS token");
1661 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1662 krb5_afslog(s->authctxt->krb5_ctx,
1663 s->authctxt->krb5_fwd_ccache, cell, NULL);
1665 krb5_afslog_home(s->authctxt->krb5_ctx,
1666 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1672 /* User has authenticated, and if a ticket was going to be
1673 * passed we would have it. KRB5CCNAME should already be set.
1674 * Now try to get an AFS token using aklog.
1676 if (k_hasafs()) { /* Do we have AFS? */
1678 aklog_path = xstrdup(KPROGDIR);
1681 * Make sure it exists before we try to run it
1683 if (stat(aklog_path, &st) == 0) {
1684 debug("Running %s to get afs token.",aklog_path);
1687 debug("%s does not exist.",aklog_path);
1692 #endif /* AFS_KRB5 */
1694 #ifdef SESSION_HOOKS
1695 if (options.session_hooks_allow &&
1696 options.session_hooks_startup_cmd)
1698 execute_session_hook(options.session_hooks_startup_cmd,
1701 options.session_hooks_shutdown_cmd != NULL);
1705 /* Change current directory to the user\'s home directory. */
1706 if (chdir(pw->pw_dir) < 0) {
1707 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1708 pw->pw_dir, strerror(errno));
1709 #ifdef HAVE_LOGIN_CAP
1710 if (login_getcapbool(lc, "requirehome", 0))
1715 if (!options.use_login)
1716 do_rc_files(s, shell);
1718 /* restore SIGPIPE for child */
1719 signal(SIGPIPE, SIG_DFL);
1721 if (options.use_login) {
1722 launch_login(pw, hostname);
1726 /* Get the last component of the shell name. */
1727 if ((shell0 = strrchr(shell, '/')) != NULL)
1733 * If we have no command, execute the shell. In this case, the shell
1734 * name to be passed in argv[0] is preceded by '-' to indicate that
1735 * this is a login shell.
1740 /* Start the shell. Set initial character to '-'. */
1743 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1744 >= sizeof(argv0) - 1) {
1750 /* Execute the shell. */
1753 execve(shell, argv, environ);
1755 /* Executing the shell failed. */
1760 * Execute the command using the user's shell. This uses the -c
1761 * option to execute the command.
1763 argv[0] = (char *) shell0;
1765 argv[2] = (char *) command;
1767 execve(shell, argv, environ);
1776 static int did_init = 0;
1778 debug("session_new: init");
1779 for (i = 0; i < MAX_SESSIONS; i++) {
1780 sessions[i].used = 0;
1784 for (i = 0; i < MAX_SESSIONS; i++) {
1785 Session *s = &sessions[i];
1787 memset(s, 0, sizeof(*s));
1793 debug("session_new: session %d", i);
1804 for (i = 0; i < MAX_SESSIONS; i++) {
1805 Session *s = &sessions[i];
1806 debug("dump: used %d session %d %p channel %d pid %ld",
1816 session_open(Authctxt *authctxt, int chanid)
1818 Session *s = session_new();
1819 debug("session_open: channel %d", chanid);
1821 error("no more sessions");
1824 s->authctxt = authctxt;
1825 s->pw = authctxt->pw;
1826 if (s->pw == NULL || !authctxt->valid)
1827 fatal("no user for session %d", s->self);
1828 debug("session_open: session %d: link with channel %d", s->self, chanid);
1834 session_by_tty(char *tty)
1837 for (i = 0; i < MAX_SESSIONS; i++) {
1838 Session *s = &sessions[i];
1839 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1840 debug("session_by_tty: session %d tty %s", i, tty);
1844 debug("session_by_tty: unknown tty %.100s", tty);
1850 session_by_channel(int id)
1853 for (i = 0; i < MAX_SESSIONS; i++) {
1854 Session *s = &sessions[i];
1855 if (s->used && s->chanid == id) {
1856 debug("session_by_channel: session %d channel %d", i, id);
1860 debug("session_by_channel: unknown channel %d", id);
1866 session_by_pid(pid_t pid)
1869 debug("session_by_pid: pid %ld", (long)pid);
1870 for (i = 0; i < MAX_SESSIONS; i++) {
1871 Session *s = &sessions[i];
1872 if (s->used && s->pid == pid)
1875 error("session_by_pid: unknown pid %ld", (long)pid);
1881 session_window_change_req(Session *s)
1883 s->col = packet_get_int();
1884 s->row = packet_get_int();
1885 s->xpixel = packet_get_int();
1886 s->ypixel = packet_get_int();
1888 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1893 session_pty_req(Session *s)
1899 debug("Allocating a pty not permitted for this authentication.");
1902 if (s->ttyfd != -1) {
1903 packet_disconnect("Protocol error: you already have a pty.");
1906 /* Get the time and hostname when the user last logged in. */
1907 if (options.print_lastlog) {
1908 s->hostname[0] = '\0';
1909 s->last_login_time = get_last_login_time(s->pw->pw_uid,
1910 s->pw->pw_name, s->hostname, sizeof(s->hostname));
1913 s->term = packet_get_string(&len);
1916 s->col = packet_get_int();
1917 s->row = packet_get_int();
1919 s->row = packet_get_int();
1920 s->col = packet_get_int();
1922 s->xpixel = packet_get_int();
1923 s->ypixel = packet_get_int();
1925 if (strcmp(s->term, "") == 0) {
1930 /* Allocate a pty and open it. */
1931 debug("Allocating pty.");
1932 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1938 error("session_pty_req: session %d alloc failed", s->self);
1941 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1943 /* for SSH1 the tty modes length is not given */
1945 n_bytes = packet_remaining();
1946 tty_parse_modes(s->ttyfd, &n_bytes);
1949 pty_setowner(s->pw, s->tty);
1951 /* Set window size from the packet. */
1952 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1955 session_proctitle(s);
1960 session_subsystem_req(Session *s)
1965 char *cmd, *subsys = packet_get_string(&len);
1969 logit("subsystem request for %.100s", subsys);
1971 for (i = 0; i < options.num_subsystems; i++) {
1972 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1973 cmd = options.subsystem_command[i];
1974 if (stat(cmd, &st) < 0) {
1975 error("subsystem: cannot stat %s: %s", cmd,
1979 debug("subsystem: exec() %s", cmd);
1980 s->is_subsystem = 1;
1988 logit("subsystem request for %.100s failed, subsystem not found",
1996 session_x11_req(Session *s)
2000 s->single_connection = packet_get_char();
2001 s->auth_proto = packet_get_string(NULL);
2002 s->auth_data = packet_get_string(NULL);
2003 s->screen = packet_get_int();
2006 success = session_setup_x11fwd(s);
2008 xfree(s->auth_proto);
2009 xfree(s->auth_data);
2010 s->auth_proto = NULL;
2011 s->auth_data = NULL;
2017 session_shell_req(Session *s)
2025 session_exec_req(Session *s)
2028 char *command = packet_get_string(&len);
2030 do_exec(s, command);
2036 session_break_req(Session *s)
2040 break_length = packet_get_int(); /* ignored */
2043 if (s->ttyfd == -1 ||
2044 tcsendbreak(s->ttyfd, 0) < 0)
2050 session_auth_agent_req(Session *s)
2052 static int called = 0;
2054 if (no_agent_forwarding_flag) {
2055 debug("session_auth_agent_req: no_agent_forwarding_flag");
2062 return auth_input_request_forwarding(s->pw);
2067 session_input_channel_req(Channel *c, const char *rtype)
2072 if ((s = session_by_channel(c->self)) == NULL) {
2073 logit("session_input_channel_req: no session %d req %.100s",
2077 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2080 * a session is in LARVAL state until a shell, a command
2081 * or a subsystem is executed
2083 if (c->type == SSH_CHANNEL_LARVAL) {
2084 if (strcmp(rtype, "shell") == 0) {
2085 success = session_shell_req(s);
2086 } else if (strcmp(rtype, "exec") == 0) {
2087 success = session_exec_req(s);
2088 } else if (strcmp(rtype, "pty-req") == 0) {
2089 success = session_pty_req(s);
2090 } else if (strcmp(rtype, "x11-req") == 0) {
2091 success = session_x11_req(s);
2092 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2093 success = session_auth_agent_req(s);
2094 } else if (strcmp(rtype, "subsystem") == 0) {
2095 success = session_subsystem_req(s);
2096 } else if (strcmp(rtype, "break") == 0) {
2097 success = session_break_req(s);
2100 if (strcmp(rtype, "window-change") == 0) {
2101 success = session_window_change_req(s);
2107 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2110 fatal("session_set_fds: called for proto != 2.0");
2112 * now that have a child and a pipe to the child,
2113 * we can activate our channel and register the fd's
2115 if (s->chanid == -1)
2116 fatal("no channel for session %d", s->self);
2117 channel_set_fds(s->chanid,
2119 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2121 CHAN_SES_WINDOW_DEFAULT);
2125 * Function to perform pty cleanup. Also called if we get aborted abnormally
2126 * (e.g., due to a dropped connection).
2129 session_pty_cleanup2(Session *s)
2132 error("session_pty_cleanup: no session");
2138 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2140 /* Record that the user has logged out. */
2142 record_logout(s->pid, s->tty, s->pw->pw_name);
2144 /* Release the pseudo-tty. */
2146 pty_release(s->tty);
2149 * Close the server side of the socket pairs. We must do this after
2150 * the pty cleanup, so that another process doesn't get this pty
2151 * while we're still cleaning up.
2153 if (close(s->ptymaster) < 0)
2154 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2156 /* unlink pty from session */
2161 session_pty_cleanup(Session *s)
2163 PRIVSEP(session_pty_cleanup2(s));
2169 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2184 return "SIG@openssh.com";
2188 session_exit_message(Session *s, int status)
2192 if ((c = channel_lookup(s->chanid)) == NULL)
2193 fatal("session_exit_message: session %d: no channel %d",
2194 s->self, s->chanid);
2195 debug("session_exit_message: session %d channel %d pid %ld",
2196 s->self, s->chanid, (long)s->pid);
2198 if (WIFEXITED(status)) {
2199 channel_request_start(s->chanid, "exit-status", 0);
2200 packet_put_int(WEXITSTATUS(status));
2202 } else if (WIFSIGNALED(status)) {
2203 channel_request_start(s->chanid, "exit-signal", 0);
2204 packet_put_cstring(sig2name(WTERMSIG(status)));
2206 packet_put_char(WCOREDUMP(status));
2207 #else /* WCOREDUMP */
2209 #endif /* WCOREDUMP */
2210 packet_put_cstring("");
2211 packet_put_cstring("");
2214 /* Some weird exit cause. Just exit. */
2215 packet_disconnect("wait returned status %04x.", status);
2218 /* disconnect channel */
2219 debug("session_exit_message: release channel %d", s->chanid);
2220 channel_cancel_cleanup(s->chanid);
2222 * emulate a write failure with 'chan_write_failed', nobody will be
2223 * interested in data we write.
2224 * Note that we must not call 'chan_read_failed', since there could
2225 * be some more data waiting in the pipe.
2227 if (c->ostate != CHAN_OUTPUT_CLOSED)
2228 chan_write_failed(c);
2233 session_close(Session *s)
2235 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2237 session_pty_cleanup(s);
2242 if (s->auth_display)
2243 xfree(s->auth_display);
2245 xfree(s->auth_data);
2247 xfree(s->auth_proto);
2249 session_proctitle(s);
2253 session_close_by_pid(pid_t pid, int status)
2255 Session *s = session_by_pid(pid);
2257 debug("session_close_by_pid: no session for pid %ld",
2261 if (s->chanid != -1)
2262 session_exit_message(s, status);
2267 * this is called when a channel dies before
2268 * the session 'child' itself dies
2271 session_close_by_channel(int id, void *arg)
2273 Session *s = session_by_channel(id);
2275 debug("session_close_by_channel: no session for id %d", id);
2278 debug("session_close_by_channel: channel %d child %ld",
2281 debug("session_close_by_channel: channel %d: has child", id);
2283 * delay detach of session, but release pty, since
2284 * the fd's to the child are already closed
2287 session_pty_cleanup(s);
2290 /* detach by removing callback */
2291 channel_cancel_cleanup(s->chanid);
2297 session_destroy_all(void (*closefunc)(Session *))
2300 for (i = 0; i < MAX_SESSIONS; i++) {
2301 Session *s = &sessions[i];
2303 if (closefunc != NULL)
2312 session_tty_list(void)
2314 static char buf[1024];
2319 for (i = 0; i < MAX_SESSIONS; i++) {
2320 Session *s = &sessions[i];
2321 if (s->used && s->ttyfd != -1) {
2323 if (strncmp(s->tty, "/dev/", 5) != 0) {
2324 cp = strrchr(s->tty, '/');
2325 cp = (cp == NULL) ? s->tty : cp + 1;
2330 strlcat(buf, ",", sizeof buf);
2331 strlcat(buf, cp, sizeof buf);
2335 strlcpy(buf, "notty", sizeof buf);
2340 session_proctitle(Session *s)
2343 error("no user for session %d", s->self);
2345 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2349 session_setup_x11fwd(Session *s)
2352 char display[512], auth_display[512];
2353 char hostname[MAXHOSTNAMELEN];
2355 if (no_x11_forwarding_flag) {
2356 packet_send_debug("X11 forwarding disabled in user configuration file.");
2359 if (!options.x11_forwarding) {
2360 debug("X11 forwarding disabled in server configuration file.");
2363 if (!options.xauth_location ||
2364 (stat(options.xauth_location, &st) == -1)) {
2365 packet_send_debug("No xauth program; cannot forward with spoofing.");
2368 if (options.use_login) {
2369 packet_send_debug("X11 forwarding disabled; "
2370 "not compatible with UseLogin=yes.");
2373 if (s->display != NULL) {
2374 debug("X11 display already set.");
2377 if (x11_create_display_inet(options.x11_display_offset,
2378 options.x11_use_localhost, s->single_connection,
2379 &s->display_number) == -1) {
2380 debug("x11_create_display_inet failed.");
2384 /* Set up a suitable value for the DISPLAY variable. */
2385 if (gethostname(hostname, sizeof(hostname)) < 0)
2386 fatal("gethostname: %.100s", strerror(errno));
2388 * auth_display must be used as the displayname when the
2389 * authorization entry is added with xauth(1). This will be
2390 * different than the DISPLAY string for localhost displays.
2392 if (options.x11_use_localhost) {
2393 snprintf(display, sizeof display, "localhost:%u.%u",
2394 s->display_number, s->screen);
2395 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2396 s->display_number, s->screen);
2397 s->display = xstrdup(display);
2398 s->auth_display = xstrdup(auth_display);
2400 #ifdef IPADDR_IN_DISPLAY
2402 struct in_addr my_addr;
2404 he = gethostbyname(hostname);
2406 error("Can't get IP address for X11 DISPLAY.");
2407 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2410 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2411 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2412 s->display_number, s->screen);
2414 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2415 s->display_number, s->screen);
2417 s->display = xstrdup(display);
2418 s->auth_display = xstrdup(display);
2425 do_authenticated2(Authctxt *authctxt)
2427 server_loop2(authctxt);
2431 do_cleanup(Authctxt *authctxt)
2433 static int called = 0;
2435 debug("do_cleanup");
2437 /* no cleanup if we're in the child for login shell */
2441 /* avoid double cleanup */
2446 if (authctxt == NULL)
2449 if (options.kerberos_ticket_cleanup &&
2451 krb5_cleanup_proc(authctxt);
2455 if (compat20 && options.gss_cleanup_creds)
2456 ssh_gssapi_cleanup_creds();
2460 if (options.use_pam) {
2462 sshpam_thread_cleanup();
2466 /* remove agent socket */
2467 auth_sock_cleanup_proc(authctxt->pw);
2470 * Cleanup ptys/utmp only if privsep is disabled,
2471 * or if running in monitor.
2473 if (!use_privsep || mm_is_monitor())
2474 session_destroy_all(session_pty_cleanup2);