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.191 2005/12/24 02:27:41 djm Exp $");
51 #include "auth-options.h"
52 #include "pathnames.h"
56 #include "serverloop.h"
60 #include "monitor_wrap.h"
62 #if defined(KRB5) && defined(USE_AFS)
72 Session *session_new(void);
73 void session_set_fds(Session *, int, int, int);
74 void session_pty_cleanup(Session *);
75 void session_proctitle(Session *);
76 int session_setup_x11fwd(Session *);
77 void do_exec_pty(Session *, const char *);
78 void do_exec_no_pty(Session *, const char *);
79 void do_exec(Session *, const char *);
80 void do_login(Session *, const char *);
81 #ifdef LOGIN_NEEDS_UTMPX
82 static void do_pre_login(Session *s);
84 void do_child(Session *, const char *);
86 int check_quietlogin(Session *, const char *);
88 static void do_authenticated1(Authctxt *);
89 static void do_authenticated2(Authctxt *);
91 static int session_pty_req(Session *);
94 static void execute_session_hook(char* prog, Authctxt *authctxt,
95 int startup, int save);
99 extern ServerOptions options;
100 extern char *__progname;
101 extern int log_stderr;
102 extern int debug_flag;
103 extern u_int utmp_len;
104 extern int startup_pipe;
105 extern void destroy_sensitive_data(void);
106 extern Buffer loginmsg;
108 /* original command from peer. */
109 const char *original_command = NULL;
112 #define MAX_SESSIONS 10
113 Session sessions[MAX_SESSIONS];
115 #ifdef HAVE_LOGIN_CAP
119 static int is_child = 0;
121 /* Name and directory of socket for authentication agent forwarding. */
122 static char *auth_sock_name = NULL;
123 static char *auth_sock_dir = NULL;
125 /* removes the agent forwarding socket */
128 auth_sock_cleanup_proc(struct passwd *pw)
130 if (auth_sock_name != NULL) {
131 temporarily_use_uid(pw);
132 unlink(auth_sock_name);
133 rmdir(auth_sock_dir);
134 auth_sock_name = NULL;
140 auth_input_request_forwarding(struct passwd * pw)
144 struct sockaddr_un sunaddr;
146 if (auth_sock_name != NULL) {
147 error("authentication forwarding requested twice.");
151 /* Temporarily drop privileged uid for mkdir/bind. */
152 temporarily_use_uid(pw);
154 /* Allocate a buffer for the socket name, and format the name. */
155 auth_sock_name = xmalloc(MAXPATHLEN);
156 auth_sock_dir = xmalloc(MAXPATHLEN);
157 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
159 /* Create private directory for socket */
160 if (mkdtemp(auth_sock_dir) == NULL) {
161 packet_send_debug("Agent forwarding disabled: "
162 "mkdtemp() failed: %.100s", strerror(errno));
164 xfree(auth_sock_name);
165 xfree(auth_sock_dir);
166 auth_sock_name = NULL;
167 auth_sock_dir = NULL;
170 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
171 auth_sock_dir, (long) getpid());
173 /* Create the socket. */
174 sock = socket(AF_UNIX, SOCK_STREAM, 0);
176 packet_disconnect("socket: %.100s", strerror(errno));
178 /* Bind it to the name. */
179 memset(&sunaddr, 0, sizeof(sunaddr));
180 sunaddr.sun_family = AF_UNIX;
181 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
183 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
184 packet_disconnect("bind: %.100s", strerror(errno));
186 /* Restore the privileged uid. */
189 /* Start listening on the socket. */
190 if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
191 packet_disconnect("listen: %.100s", strerror(errno));
193 /* Allocate a channel for the authentication agent socket. */
194 nc = channel_new("auth socket",
195 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
196 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
197 0, "auth socket", 1);
198 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
203 display_loginmsg(void)
205 if (buffer_len(&loginmsg) > 0) {
206 buffer_append(&loginmsg, "\0", 1);
207 printf("%s", (char *)buffer_ptr(&loginmsg));
208 buffer_clear(&loginmsg);
213 do_authenticated(Authctxt *authctxt)
215 setproctitle("%s", authctxt->pw->pw_name);
217 /* setup the channel layer */
218 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
219 channel_permit_all_opens();
222 do_authenticated2(authctxt);
224 do_authenticated1(authctxt);
227 if (options.session_hooks_allow &&
228 options.session_hooks_shutdown_cmd)
230 execute_session_hook(options.session_hooks_shutdown_cmd,
232 /* startup = */ 0, /* save = */ 0);
234 if (authctxt->session_env_file)
236 free(authctxt->session_env_file);
241 do_cleanup(authctxt);
245 * Prepares for an interactive session. This is called after the user has
246 * been successfully authenticated. During this message exchange, pseudo
247 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
248 * are requested, etc.
251 do_authenticated1(Authctxt *authctxt)
255 int success, type, screen_flag;
256 int enable_compression_after_reply = 0;
257 u_int proto_len, data_len, dlen, compression_level = 0;
261 error("no more sessions");
264 s->authctxt = authctxt;
265 s->pw = authctxt->pw;
268 * We stay in this loop until the client requests to execute a shell
274 /* Get a packet from the client. */
275 type = packet_read();
277 /* Process the packet. */
279 case SSH_CMSG_REQUEST_COMPRESSION:
280 compression_level = packet_get_int();
282 if (compression_level < 1 || compression_level > 9) {
283 packet_send_debug("Received invalid compression level %d.",
287 if (options.compression == COMP_NONE) {
288 debug2("compression disabled");
291 /* Enable compression after we have responded with SUCCESS. */
292 enable_compression_after_reply = 1;
296 case SSH_CMSG_REQUEST_PTY:
297 success = session_pty_req(s);
300 case SSH_CMSG_X11_REQUEST_FORWARDING:
301 s->auth_proto = packet_get_string(&proto_len);
302 s->auth_data = packet_get_string(&data_len);
304 screen_flag = packet_get_protocol_flags() &
305 SSH_PROTOFLAG_SCREEN_NUMBER;
306 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
308 if (packet_remaining() == 4) {
310 debug2("Buggy client: "
311 "X11 screen flag missing");
312 s->screen = packet_get_int();
317 success = session_setup_x11fwd(s);
319 xfree(s->auth_proto);
321 s->auth_proto = NULL;
326 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
327 if (no_agent_forwarding_flag || compat13) {
328 debug("Authentication agent forwarding not permitted for this authentication.");
331 debug("Received authentication agent forwarding request.");
332 success = auth_input_request_forwarding(s->pw);
335 case SSH_CMSG_PORT_FORWARD_REQUEST:
336 if (no_port_forwarding_flag) {
337 debug("Port forwarding not permitted for this authentication.");
340 if (!options.allow_tcp_forwarding) {
341 debug("Port forwarding not permitted.");
344 debug("Received TCP/IP port forwarding request.");
345 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
349 case SSH_CMSG_MAX_PACKET_SIZE:
350 if (packet_set_maxsize(packet_get_int()) > 0)
354 case SSH_CMSG_EXEC_SHELL:
355 case SSH_CMSG_EXEC_CMD:
356 if (type == SSH_CMSG_EXEC_CMD) {
357 command = packet_get_string(&dlen);
358 debug("Exec command '%.500s'", command);
370 * Any unknown messages in this phase are ignored,
371 * and a failure message is returned.
373 logit("Unknown packet type received after authentication: %d", type);
375 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
379 /* Enable compression now that we have replied if appropriate. */
380 if (enable_compression_after_reply) {
381 enable_compression_after_reply = 0;
382 packet_start_compression(compression_level);
388 * This is called to fork and execute a command when we have no tty. This
389 * will call do_child from the child, and server_loop from the parent after
390 * setting up file descriptors and such.
393 do_exec_no_pty(Session *s, const char *command)
398 int pin[2], pout[2], perr[2];
399 /* Allocate pipes for communicating with the program. */
400 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
401 packet_disconnect("Could not create pipes: %.100s",
403 #else /* USE_PIPES */
404 int inout[2], err[2];
405 /* Uses socket pairs to communicate with the program. */
406 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
407 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
408 packet_disconnect("Could not create socket pairs: %.100s",
410 #endif /* USE_PIPES */
412 fatal("do_exec_no_pty: no session");
414 session_proctitle(s);
417 if (options.use_pam && !use_privsep)
421 /* Fork the child. */
422 if ((pid = fork()) == 0) {
425 /* Child. Reinitialize the log since the pid has changed. */
426 log_init(__progname, options.log_level, options.log_facility, log_stderr);
429 * Create a new session and process group since the 4.4BSD
430 * setlogin() affects the entire process group.
433 error("setsid failed: %.100s", strerror(errno));
437 * Redirect stdin. We close the parent side of the socket
438 * pair, and make the child side the standard input.
441 if (dup2(pin[0], 0) < 0)
442 perror("dup2 stdin");
445 /* Redirect stdout. */
447 if (dup2(pout[1], 1) < 0)
448 perror("dup2 stdout");
451 /* Redirect stderr. */
453 if (dup2(perr[1], 2) < 0)
454 perror("dup2 stderr");
456 #else /* USE_PIPES */
458 * Redirect stdin, stdout, and stderr. Stdin and stdout will
459 * use the same socket, as some programs (particularly rdist)
460 * seem to depend on it.
464 if (dup2(inout[0], 0) < 0) /* stdin */
465 perror("dup2 stdin");
466 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
467 perror("dup2 stdout");
468 if (dup2(err[0], 2) < 0) /* stderr */
469 perror("dup2 stderr");
470 #endif /* USE_PIPES */
473 cray_init_job(s->pw); /* set up cray jid and tmpdir */
476 /* Do processing for the child (exec command etc). */
477 do_child(s, command);
481 signal(WJSIGNAL, cray_job_termination_handler);
485 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
488 packet_disconnect("fork failed: %.100s", strerror(errno));
490 /* Set interactive/non-interactive mode. */
491 packet_set_interactive(s->display != NULL);
493 /* We are the parent. Close the child sides of the pipes. */
499 if (s->is_subsystem) {
503 session_set_fds(s, pin[1], pout[0], perr[0]);
505 /* Enter the interactive session. */
506 server_loop(pid, pin[1], pout[0], perr[0]);
507 /* server_loop has closed pin[1], pout[0], and perr[0]. */
509 #else /* USE_PIPES */
510 /* We are the parent. Close the child sides of the socket pairs. */
515 * Clear loginmsg, since it's the child's responsibility to display
516 * it to the user, otherwise multiple sessions may accumulate
517 * multiple copies of the login messages.
519 buffer_clear(&loginmsg);
522 * Enter the interactive session. Note: server_loop must be able to
523 * handle the case that fdin and fdout are the same.
526 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
528 server_loop(pid, inout[1], inout[1], err[1]);
529 /* server_loop has closed inout[1] and err[1]. */
531 #endif /* USE_PIPES */
535 * This is called to fork and execute a command when we have a tty. This
536 * will call do_child from the child, and server_loop from the parent after
537 * setting up file descriptors, controlling tty, updating wtmp, utmp,
538 * lastlog, and other such operations.
541 do_exec_pty(Session *s, const char *command)
543 int fdout, ptyfd, ttyfd, ptymaster;
547 fatal("do_exec_pty: no session");
552 if (options.use_pam) {
553 do_pam_set_tty(s->tty);
559 /* Fork the child. */
560 if ((pid = fork()) == 0) {
563 /* Child. Reinitialize the log because the pid has changed. */
564 log_init(__progname, options.log_level, options.log_facility, log_stderr);
565 /* Close the master side of the pseudo tty. */
568 /* Make the pseudo tty our controlling tty. */
569 pty_make_controlling_tty(&ttyfd, s->tty);
571 /* Redirect stdin/stdout/stderr from the pseudo tty. */
572 if (dup2(ttyfd, 0) < 0)
573 error("dup2 stdin: %s", strerror(errno));
574 if (dup2(ttyfd, 1) < 0)
575 error("dup2 stdout: %s", strerror(errno));
576 if (dup2(ttyfd, 2) < 0)
577 error("dup2 stderr: %s", strerror(errno));
579 /* Close the extra descriptor for the pseudo tty. */
582 /* record login, etc. similar to login(1) */
584 if (!(options.use_login && command == NULL)) {
586 cray_init_job(s->pw); /* set up cray jid and tmpdir */
588 do_login(s, command);
590 # ifdef LOGIN_NEEDS_UTMPX
596 /* Do common processing for the child, such as execing the command. */
597 do_child(s, command);
601 signal(WJSIGNAL, cray_job_termination_handler);
605 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
608 packet_disconnect("fork failed: %.100s", strerror(errno));
611 /* Parent. Close the slave side of the pseudo tty. */
615 * Create another descriptor of the pty master side for use as the
616 * standard input. We could use the original descriptor, but this
617 * simplifies code in server_loop. The descriptor is bidirectional.
621 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
623 /* we keep a reference to the pty master */
624 ptymaster = dup(ptyfd);
626 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
627 s->ptymaster = ptymaster;
629 /* Enter interactive session. */
630 packet_set_interactive(1);
632 session_set_fds(s, ptyfd, fdout, -1);
634 server_loop(pid, ptyfd, fdout, -1);
635 /* server_loop _has_ closed ptyfd and fdout. */
639 #ifdef LOGIN_NEEDS_UTMPX
641 do_pre_login(Session *s)
644 struct sockaddr_storage from;
645 pid_t pid = getpid();
648 * Get IP address of client. If the connection is not a socket, let
649 * the address be 0.0.0.0.
651 memset(&from, 0, sizeof(from));
652 fromlen = sizeof(from);
653 if (packet_connection_is_on_socket()) {
654 if (getpeername(packet_get_connection_in(),
655 (struct sockaddr *) & from, &fromlen) < 0) {
656 debug("getpeername: %.100s", strerror(errno));
661 record_utmp_only(pid, s->tty, s->pw->pw_name,
662 get_remote_name_or_ip(utmp_len, options.use_dns),
663 (struct sockaddr *)&from, fromlen);
668 * This is called to fork and execute a command. If another command is
669 * to be forced, execute that instead.
672 do_exec(Session *s, const char *command)
674 if (forced_command) {
675 original_command = command;
676 command = forced_command;
677 debug("Forced command '%.900s'", command);
680 #if defined(SESSION_HOOKS)
681 if (options.session_hooks_allow &&
682 (options.session_hooks_startup_cmd ||
683 options.session_hooks_shutdown_cmd))
691 "/tmp/ssh_env_%d%d%d",
695 } while (stat(env_file, &st)==0);
696 s->authctxt->session_env_file = strdup(env_file);
700 #ifdef SSH_AUDIT_EVENTS
702 PRIVSEP(audit_run_command(command));
703 else if (s->ttyfd == -1) {
704 char *shell = s->pw->pw_shell;
706 if (shell[0] == '\0') /* empty shell means /bin/sh */
708 PRIVSEP(audit_run_command(shell));
713 do_exec_pty(s, command);
715 do_exec_no_pty(s, command);
717 original_command = NULL;
720 * Clear loginmsg: it's the child's responsibility to display
721 * it to the user, otherwise multiple sessions may accumulate
722 * multiple copies of the login messages.
724 buffer_clear(&loginmsg);
727 /* administrative, login(1)-like work */
729 do_login(Session *s, const char *command)
732 struct sockaddr_storage from;
733 struct passwd * pw = s->pw;
734 pid_t pid = getpid();
737 * Get IP address of client. If the connection is not a socket, let
738 * the address be 0.0.0.0.
740 memset(&from, 0, sizeof(from));
741 fromlen = sizeof(from);
742 if (packet_connection_is_on_socket()) {
743 if (getpeername(packet_get_connection_in(),
744 (struct sockaddr *) & from, &fromlen) < 0) {
745 debug("getpeername: %.100s", strerror(errno));
750 /* Record that there was a login on that tty from the remote host. */
752 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
753 get_remote_name_or_ip(utmp_len,
755 (struct sockaddr *)&from, fromlen);
759 * If password change is needed, do it now.
760 * This needs to occur before the ~/.hushlogin check.
762 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
765 s->authctxt->force_pwchange = 0;
766 /* XXX - signal [net] parent to enable forwardings */
770 if (check_quietlogin(s, command))
779 * Display the message of the day.
787 if (options.print_motd) {
788 #ifdef HAVE_LOGIN_CAP
789 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
792 f = fopen("/etc/motd", "r");
795 while (fgets(buf, sizeof(buf), f))
804 * Check for quiet login, either .hushlogin or command given.
807 check_quietlogin(Session *s, const char *command)
810 struct passwd *pw = s->pw;
813 /* Return 1 if .hushlogin exists or a command given. */
816 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
817 #ifdef HAVE_LOGIN_CAP
818 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
821 if (stat(buf, &st) >= 0)
828 * Sets the value of the given variable in the environment. If the variable
829 * already exists, its value is overriden.
832 child_set_env(char ***envp, u_int *envsizep, const char *name,
840 * If we're passed an uninitialized list, allocate a single null
841 * entry before continuing.
843 if (*envp == NULL && *envsizep == 0) {
844 *envp = xmalloc(sizeof(char *));
850 * Find the slot where the value should be stored. If the variable
851 * already exists, we reuse the slot; otherwise we append a new slot
852 * at the end of the array, expanding if necessary.
855 namelen = strlen(name);
856 for (i = 0; env[i]; i++)
857 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
860 /* Reuse the slot. */
863 /* New variable. Expand if necessary. */
865 if (i >= envsize - 1) {
867 fatal("child_set_env: too many env vars");
869 env = (*envp) = xrealloc(env, envsize * sizeof(char *));
872 /* Need to set the NULL pointer at end of array beyond the new slot. */
876 /* Allocate space and format the variable in the appropriate slot. */
877 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
878 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
882 * Reads environment variables from the given file and adds/overrides them
883 * into the environment. If the file does not exist, this does nothing.
884 * Otherwise, it must consist of empty lines, comments (line starts with '#')
885 * and assignments of the form name=value. No other forms are allowed.
888 read_environment_file(char ***env, u_int *envsize,
889 const char *filename)
896 f = fopen(filename, "r");
900 while (fgets(buf, sizeof(buf), f)) {
902 fatal("Too many lines in environment file %s", filename);
903 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
905 if (!*cp || *cp == '#' || *cp == '\n')
907 if (strchr(cp, '\n'))
908 *strchr(cp, '\n') = '\0';
909 value = strchr(cp, '=');
911 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
916 * Replace the equals sign by nul, and advance value to
921 child_set_env(env, envsize, cp, value);
927 #define SSH_SESSION_ENV_FILE "SSH_SESSION_ENV_FILE"
929 typedef enum { no_op, execute, clear_env, restore_env,
930 read_env, save_or_rm_env } session_action_t;
932 static session_action_t action_order[2][5] = {
933 { clear_env, read_env, execute, save_or_rm_env, restore_env }, /*shutdown*/
934 { execute, read_env, save_or_rm_env, no_op, no_op } /*startup */
938 void execute_session_hook(char* prog, Authctxt *authctxt,
939 int startup, int save)
941 extern char **environ;
944 char **saved_env, **tmpenv;
945 char *env_file = authctxt->session_env_file;
950 switch (action_order[startup][i])
963 authctxt->pw->pw_shell,
966 debug("executing session hook: [%s]", buf);
967 setenv(SSH_SESSION_ENV_FILE, env_file, /* overwrite = */ 1);
969 /* flusing is recommended in the popen(3) man page, to avoid
970 intermingling of output */
973 if ((fp=popen(buf, "w")) == NULL)
975 perror("Unable to run session hook");
979 debug2("session hook executed, status=%d", status);
980 unsetenv(SSH_SESSION_ENV_FILE);
986 tmpenv = (char**) malloc(sizeof(char*));
997 if (status==0 && stat(env_file, &st)==0)
1001 debug("reading environment from %s", env_file);
1002 while (environ[envsize++]) ;
1003 read_environment_file(&environ, &envsize, env_file);
1007 case save_or_rm_env:
1008 if (status==0 && save)
1013 debug2("saving environment to %s", env_file);
1014 if ((fp = fopen(env_file, "w")) == NULL) /* hmm: file perms? */
1016 perror("Unable to save session hook info");
1018 while (environ[envcount])
1020 fprintf(fp, "%s\n", environ[envcount++]);
1025 else if (stat(env_file, &st)==0)
1027 debug2("removing environment file %s", env_file);
1037 #ifdef HAVE_ETC_DEFAULT_LOGIN
1039 * Return named variable from specified environment, or NULL if not present.
1042 child_get_env(char **env, const char *name)
1048 for (i=0; env[i] != NULL; i++)
1049 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
1050 return(env[i] + len + 1);
1055 * Read /etc/default/login.
1056 * We pick up the PATH (or SUPATH for root) and UMASK.
1059 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
1061 char **tmpenv = NULL, *var;
1062 u_int i, tmpenvsize = 0;
1066 * We don't want to copy the whole file to the child's environment,
1067 * so we use a temporary environment and copy the variables we're
1070 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
1076 var = child_get_env(tmpenv, "SUPATH");
1078 var = child_get_env(tmpenv, "PATH");
1080 child_set_env(env, envsize, "PATH", var);
1082 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
1083 if (sscanf(var, "%5lo", &mask) == 1)
1084 umask((mode_t)mask);
1086 for (i = 0; tmpenv[i] != NULL; i++)
1090 #endif /* HAVE_ETC_DEFAULT_LOGIN */
1093 copy_environment(char **source, char ***env, u_int *envsize)
1095 char *var_name, *var_val;
1101 for(i = 0; source[i] != NULL; i++) {
1102 var_name = xstrdup(source[i]);
1103 if ((var_val = strstr(var_name, "=")) == NULL) {
1109 debug3("Copy environment: %s=%s", var_name, var_val);
1110 child_set_env(env, envsize, var_name, var_val);
1117 do_setup_env(Session *s, const char *shell)
1121 char **env, *laddr, *path = NULL;
1122 struct passwd *pw = s->pw;
1124 /* Initialize the environment. */
1126 env = xmalloc(envsize * sizeof(char *));
1131 * The Windows environment contains some setting which are
1132 * important for a running system. They must not be dropped.
1137 p = fetch_windows_environment();
1138 copy_environment(p, &env, &envsize);
1139 free_windows_environment(p);
1144 /* Allow any GSSAPI methods that we've used to alter
1145 * the childs environment as they see fit
1147 ssh_gssapi_do_child(&env, &envsize);
1150 if (!options.use_login) {
1151 /* Set basic environment. */
1152 for (i = 0; i < s->num_env; i++)
1153 child_set_env(&env, &envsize, s->env[i].name,
1156 child_set_env(&env, &envsize, "USER", pw->pw_name);
1157 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1159 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1161 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1162 #ifdef HAVE_LOGIN_CAP
1163 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1164 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1166 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1167 #else /* HAVE_LOGIN_CAP */
1168 # ifndef HAVE_CYGWIN
1170 * There's no standard path on Windows. The path contains
1171 * important components pointing to the system directories,
1172 * needed for loading shared libraries. So the path better
1173 * remains intact here.
1175 # ifdef HAVE_ETC_DEFAULT_LOGIN
1176 read_etc_default_login(&env, &envsize, pw->pw_uid);
1177 path = child_get_env(env, "PATH");
1178 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1179 if (path == NULL || *path == '\0') {
1180 child_set_env(&env, &envsize, "PATH",
1181 s->pw->pw_uid == 0 ?
1182 SUPERUSER_PATH : _PATH_STDPATH);
1184 # endif /* HAVE_CYGWIN */
1185 #endif /* HAVE_LOGIN_CAP */
1187 snprintf(buf, sizeof buf, "%.200s/%.50s",
1188 _PATH_MAILDIR, pw->pw_name);
1189 child_set_env(&env, &envsize, "MAIL", buf);
1191 /* Normal systems set SHELL by default. */
1192 child_set_env(&env, &envsize, "SHELL", shell);
1195 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1197 #ifdef GSI /* GSI shared libs typically installed in non-system locations. */
1201 if ((cp = getenv("LD_LIBRARY_PATH")) != NULL)
1202 child_set_env(&env, &envsize, "LD_LIBRARY_PATH", cp);
1203 if ((cp = getenv("LIBPATH")) != NULL)
1204 child_set_env(&env, &envsize, "LIBPATH", cp);
1205 if ((cp = getenv("SHLIB_PATH")) != NULL)
1206 child_set_env(&env, &envsize, "SHLIB_PATH", cp);
1207 if ((cp = getenv("LD_LIBRARYN32_PATH")) != NULL)
1208 child_set_env(&env, &envsize, "LD_LIBRARYN32_PATH",cp);
1209 if ((cp = getenv("LD_LIBRARY64_PATH")) != NULL)
1210 child_set_env(&env, &envsize, "LD_LIBRARY64_PATH",cp);
1214 /* Set custom environment options from RSA authentication. */
1215 if (!options.use_login) {
1216 while (custom_environment) {
1217 struct envstring *ce = custom_environment;
1220 for (i = 0; str[i] != '=' && str[i]; i++)
1222 if (str[i] == '=') {
1224 child_set_env(&env, &envsize, str, str + i + 1);
1226 custom_environment = ce->next;
1232 /* SSH_CLIENT deprecated */
1233 snprintf(buf, sizeof buf, "%.50s %d %d",
1234 get_remote_ipaddr(), get_remote_port(), get_local_port());
1235 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1237 laddr = get_local_ipaddr(packet_get_connection_in());
1238 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1239 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1241 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1244 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1246 child_set_env(&env, &envsize, "TERM", s->term);
1248 child_set_env(&env, &envsize, "DISPLAY", s->display);
1249 if (original_command)
1250 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1254 if (cray_tmpdir[0] != '\0')
1255 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1256 #endif /* _UNICOS */
1259 * Since we clear KRB5CCNAME at startup, if it's set now then it
1260 * must have been set by a native authentication method (eg AIX or
1261 * SIA), so copy it to the child.
1266 if ((cp = getenv("KRB5CCNAME")) != NULL)
1267 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1274 if ((cp = getenv("AUTHSTATE")) != NULL)
1275 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1276 read_environment_file(&env, &envsize, "/etc/environment");
1280 if (s->authctxt->krb5_ccname)
1281 child_set_env(&env, &envsize, "KRB5CCNAME",
1282 s->authctxt->krb5_ccname);
1286 * Pull in any environment variables that may have
1289 if (options.use_pam) {
1292 p = fetch_pam_child_environment();
1293 copy_environment(p, &env, &envsize);
1294 free_pam_environment(p);
1296 p = fetch_pam_environment();
1297 copy_environment(p, &env, &envsize);
1298 free_pam_environment(p);
1300 #endif /* USE_PAM */
1302 if (auth_sock_name != NULL)
1303 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1306 /* read $HOME/.ssh/environment. */
1307 if (options.permit_user_env && !options.use_login) {
1308 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1309 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1310 read_environment_file(&env, &envsize, buf);
1313 /* dump the environment */
1314 fprintf(stderr, "Environment:\n");
1315 for (i = 0; env[i]; i++)
1316 fprintf(stderr, " %.200s\n", env[i]);
1322 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1323 * first in this order).
1326 do_rc_files(Session *s, const char *shell)
1334 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1336 /* ignore _PATH_SSH_USER_RC for subsystems */
1337 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1338 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1339 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1341 fprintf(stderr, "Running %s\n", cmd);
1342 f = popen(cmd, "w");
1345 fprintf(f, "%s %s\n", s->auth_proto,
1349 fprintf(stderr, "Could not run %s\n",
1351 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1353 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1354 _PATH_SSH_SYSTEM_RC);
1355 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1358 fprintf(f, "%s %s\n", s->auth_proto,
1362 fprintf(stderr, "Could not run %s\n",
1363 _PATH_SSH_SYSTEM_RC);
1364 } else if (do_xauth && options.xauth_location != NULL) {
1365 /* Add authority data to .Xauthority if appropriate. */
1368 "Running %.500s remove %.100s\n",
1369 options.xauth_location, s->auth_display);
1371 "%.500s add %.100s %.100s %.100s\n",
1372 options.xauth_location, s->auth_display,
1373 s->auth_proto, s->auth_data);
1375 snprintf(cmd, sizeof cmd, "%s -q -",
1376 options.xauth_location);
1377 f = popen(cmd, "w");
1379 fprintf(f, "remove %s\n",
1381 fprintf(f, "add %s %s %s\n",
1382 s->auth_display, s->auth_proto,
1386 fprintf(stderr, "Could not run %s\n",
1393 do_nologin(struct passwd *pw)
1398 #ifdef HAVE_LOGIN_CAP
1399 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1400 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1401 _PATH_NOLOGIN), "r");
1404 f = fopen(_PATH_NOLOGIN, "r");
1407 /* /etc/nologin exists. Print its contents and exit. */
1408 logit("User %.100s not allowed because %s exists",
1409 pw->pw_name, _PATH_NOLOGIN);
1410 while (fgets(buf, sizeof(buf), f))
1418 /* Set login name, uid, gid, and groups. */
1420 do_setusercontext(struct passwd *pw)
1423 if (getuid() == 0 || geteuid() == 0)
1424 #endif /* HAVE_CYGWIN */
1427 #ifdef HAVE_SETPCRED
1428 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1429 fatal("Failed to set process credentials");
1430 #endif /* HAVE_SETPCRED */
1431 #ifdef HAVE_LOGIN_CAP
1436 if (options.gss_authentication) {
1437 temporarily_use_uid(pw);
1438 ssh_gssapi_storecreds();
1443 if (options.use_pam) {
1447 # endif /* USE_PAM */
1448 if (setusercontext(lc, pw, pw->pw_uid,
1449 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1450 perror("unable to set user context");
1454 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1455 /* Sets login uid for accounting */
1456 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1457 error("setluid: %s", strerror(errno));
1458 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1460 if (setlogin(pw->pw_name) < 0)
1461 error("setlogin failed: %s", strerror(errno));
1462 if (setgid(pw->pw_gid) < 0) {
1466 /* Initialize the group list. */
1467 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1468 perror("initgroups");
1473 if (options.gss_authentication) {
1474 temporarily_use_uid(pw);
1475 ssh_gssapi_storecreds();
1481 * PAM credentials may take the form of supplementary groups.
1482 * These will have been wiped by the above initgroups() call.
1483 * Reestablish them here.
1485 if (options.use_pam) {
1489 # endif /* USE_PAM */
1490 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1491 irix_setusercontext(pw);
1492 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1496 #if defined(HAVE_LIBIAF) && !defined(BROKEN_LIBIAF)
1497 if (set_id(pw->pw_name) != 0) {
1500 #endif /* HAVE_LIBIAF && !BROKEN_LIBIAF */
1501 /* Permanently switch to the desired uid. */
1502 permanently_set_uid(pw);
1509 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1510 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1514 do_pwchange(Session *s)
1517 fprintf(stderr, "WARNING: Your password has expired.\n");
1518 if (s->ttyfd != -1) {
1520 "You must change your password now and login again!\n");
1521 #ifdef PASSWD_NEEDS_USERNAME
1522 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1525 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1530 "Password change required but no TTY available.\n");
1536 launch_login(struct passwd *pw, const char *hostname)
1538 /* Launch login(1). */
1540 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1541 #ifdef xxxLOGIN_NEEDS_TERM
1542 (s->term ? s->term : "unknown"),
1543 #endif /* LOGIN_NEEDS_TERM */
1544 #ifdef LOGIN_NO_ENDOPT
1545 "-p", "-f", pw->pw_name, (char *)NULL);
1547 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1550 /* Login couldn't be executed, die. */
1557 child_close_fds(void)
1561 if (packet_get_connection_in() == packet_get_connection_out())
1562 close(packet_get_connection_in());
1564 close(packet_get_connection_in());
1565 close(packet_get_connection_out());
1568 * Close all descriptors related to channels. They will still remain
1569 * open in the parent.
1571 /* XXX better use close-on-exec? -markus */
1572 channel_close_all();
1575 * Close any extra file descriptors. Note that there may still be
1576 * descriptors left by system functions. They will be closed later.
1581 * Close any extra open file descriptors so that we don't have them
1582 * hanging around in clients. Note that we want to do this after
1583 * initgroups, because at least on Solaris 2.3 it leaves file
1586 for (i = 3; i < 64; i++)
1591 * Performs common processing for the child, such as setting up the
1592 * environment, closing extra file descriptors, setting the user and group
1593 * ids, and executing the command or shell.
1596 do_child(Session *s, const char *command)
1598 extern char **environ;
1601 const char *shell, *shell0, *hostname = NULL;
1602 struct passwd *pw = s->pw;
1605 /* Default place to look for aklog. */
1607 #define KPROGDIR AKLOG_PATH
1609 #define KPROGDIR "/usr/bin/aklog"
1610 #endif /* AKLOG_PATH */
1614 #endif /* AFS_KRB5 */
1616 /* remove hostkey from the child's memory */
1617 destroy_sensitive_data();
1619 /* Force a password change */
1620 if (s->authctxt->force_pwchange) {
1621 do_setusercontext(pw);
1627 /* login(1) is only called if we execute the login shell */
1628 if (options.use_login && command != NULL)
1629 options.use_login = 0;
1632 cray_setup(pw->pw_uid, pw->pw_name, command);
1633 #endif /* _UNICOS */
1636 * Login(1) does this as well, and it needs uid 0 for the "-h"
1637 * switch, so we let login(1) to this for us.
1639 if (!options.use_login) {
1641 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1642 if (!check_quietlogin(s, command))
1644 #else /* HAVE_OSF_SIA */
1645 /* When PAM is enabled we rely on it to do the nologin check */
1646 if (!options.use_pam)
1648 do_setusercontext(pw);
1650 * PAM session modules in do_setusercontext may have
1651 * generated messages, so if this in an interactive
1652 * login then display them too.
1654 if (!check_quietlogin(s, command))
1656 #endif /* HAVE_OSF_SIA */
1660 if (options.use_pam && !options.use_login && !is_pam_session_open()) {
1661 debug3("PAM session not opened, exiting");
1668 * Get the shell from the password data. An empty shell field is
1669 * legal, and means /bin/sh.
1671 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1674 * Make sure $SHELL points to the shell from the password file,
1675 * even if shell is overridden from login.conf
1677 env = do_setup_env(s, shell);
1679 #ifdef HAVE_LOGIN_CAP
1680 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1683 /* we have to stash the hostname before we close our socket. */
1684 if (options.use_login)
1685 hostname = get_remote_name_or_ip(utmp_len,
1688 * Close the connection descriptors; note that this is the child, and
1689 * the server will still have the socket open, and it is important
1690 * that we do not shutdown it. Note that the descriptors cannot be
1691 * closed before building the environment, as we call
1692 * get_remote_ipaddr there.
1697 * Must take new environment into use so that .ssh/rc,
1698 * /etc/ssh/sshrc and xauth are run in the proper environment.
1702 #if defined(KRB5) && defined(USE_AFS)
1704 * At this point, we check to see if AFS is active and if we have
1705 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1706 * if we can (and need to) extend the ticket into an AFS token. If
1707 * we don't do this, we run into potential problems if the user's
1708 * home directory is in AFS and it's not world-readable.
1711 if (options.kerberos_get_afs_token && k_hasafs() &&
1712 (s->authctxt->krb5_ctx != NULL)) {
1715 debug("Getting AFS token");
1719 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1720 krb5_afslog(s->authctxt->krb5_ctx,
1721 s->authctxt->krb5_fwd_ccache, cell, NULL);
1723 krb5_afslog_home(s->authctxt->krb5_ctx,
1724 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1730 /* User has authenticated, and if a ticket was going to be
1731 * passed we would have it. KRB5CCNAME should already be set.
1732 * Now try to get an AFS token using aklog.
1734 if (k_hasafs()) { /* Do we have AFS? */
1736 aklog_path = xstrdup(KPROGDIR);
1739 * Make sure it exists before we try to run it
1741 if (stat(aklog_path, &st) == 0) {
1742 debug("Running %s to get afs token.",aklog_path);
1745 debug("%s does not exist.",aklog_path);
1750 #endif /* AFS_KRB5 */
1752 #ifdef SESSION_HOOKS
1753 if (options.session_hooks_allow &&
1754 options.session_hooks_startup_cmd)
1756 execute_session_hook(options.session_hooks_startup_cmd,
1759 options.session_hooks_shutdown_cmd != NULL);
1763 /* Change current directory to the user's home directory. */
1764 if (chdir(pw->pw_dir) < 0) {
1765 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1766 pw->pw_dir, strerror(errno));
1767 #ifdef HAVE_LOGIN_CAP
1768 if (login_getcapbool(lc, "requirehome", 0))
1773 if (!options.use_login)
1774 do_rc_files(s, shell);
1776 /* restore SIGPIPE for child */
1777 signal(SIGPIPE, SIG_DFL);
1779 if (options.use_login) {
1780 launch_login(pw, hostname);
1784 /* Get the last component of the shell name. */
1785 if ((shell0 = strrchr(shell, '/')) != NULL)
1791 * If we have no command, execute the shell. In this case, the shell
1792 * name to be passed in argv[0] is preceded by '-' to indicate that
1793 * this is a login shell.
1798 /* Start the shell. Set initial character to '-'. */
1801 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1802 >= sizeof(argv0) - 1) {
1808 /* Execute the shell. */
1811 execve(shell, argv, environ);
1813 /* Executing the shell failed. */
1818 * Execute the command using the user's shell. This uses the -c
1819 * option to execute the command.
1821 argv[0] = (char *) shell0;
1823 argv[2] = (char *) command;
1825 execve(shell, argv, environ);
1834 static int did_init = 0;
1836 debug("session_new: init");
1837 for (i = 0; i < MAX_SESSIONS; i++) {
1838 sessions[i].used = 0;
1842 for (i = 0; i < MAX_SESSIONS; i++) {
1843 Session *s = &sessions[i];
1845 memset(s, 0, sizeof(*s));
1851 s->x11_chanids = NULL;
1852 debug("session_new: session %d", i);
1863 for (i = 0; i < MAX_SESSIONS; i++) {
1864 Session *s = &sessions[i];
1865 debug("dump: used %d session %d %p channel %d pid %ld",
1875 session_open(Authctxt *authctxt, int chanid)
1877 Session *s = session_new();
1878 debug("session_open: channel %d", chanid);
1880 error("no more sessions");
1883 s->authctxt = authctxt;
1884 s->pw = authctxt->pw;
1885 if (s->pw == NULL || !authctxt->valid)
1886 fatal("no user for session %d", s->self);
1887 debug("session_open: session %d: link with channel %d", s->self, chanid);
1893 session_by_tty(char *tty)
1896 for (i = 0; i < MAX_SESSIONS; i++) {
1897 Session *s = &sessions[i];
1898 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1899 debug("session_by_tty: session %d tty %s", i, tty);
1903 debug("session_by_tty: unknown tty %.100s", tty);
1909 session_by_channel(int id)
1912 for (i = 0; i < MAX_SESSIONS; i++) {
1913 Session *s = &sessions[i];
1914 if (s->used && s->chanid == id) {
1915 debug("session_by_channel: session %d channel %d", i, id);
1919 debug("session_by_channel: unknown channel %d", id);
1925 session_by_x11_channel(int id)
1929 for (i = 0; i < MAX_SESSIONS; i++) {
1930 Session *s = &sessions[i];
1932 if (s->x11_chanids == NULL || !s->used)
1934 for (j = 0; s->x11_chanids[j] != -1; j++) {
1935 if (s->x11_chanids[j] == id) {
1936 debug("session_by_x11_channel: session %d "
1937 "channel %d", s->self, id);
1942 debug("session_by_x11_channel: unknown channel %d", id);
1948 session_by_pid(pid_t pid)
1951 debug("session_by_pid: pid %ld", (long)pid);
1952 for (i = 0; i < MAX_SESSIONS; i++) {
1953 Session *s = &sessions[i];
1954 if (s->used && s->pid == pid)
1957 error("session_by_pid: unknown pid %ld", (long)pid);
1963 session_window_change_req(Session *s)
1965 s->col = packet_get_int();
1966 s->row = packet_get_int();
1967 s->xpixel = packet_get_int();
1968 s->ypixel = packet_get_int();
1970 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1975 session_pty_req(Session *s)
1981 debug("Allocating a pty not permitted for this authentication.");
1984 if (s->ttyfd != -1) {
1985 packet_disconnect("Protocol error: you already have a pty.");
1989 s->term = packet_get_string(&len);
1992 s->col = packet_get_int();
1993 s->row = packet_get_int();
1995 s->row = packet_get_int();
1996 s->col = packet_get_int();
1998 s->xpixel = packet_get_int();
1999 s->ypixel = packet_get_int();
2001 if (strcmp(s->term, "") == 0) {
2006 /* Allocate a pty and open it. */
2007 debug("Allocating pty.");
2008 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
2014 error("session_pty_req: session %d alloc failed", s->self);
2017 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
2019 /* for SSH1 the tty modes length is not given */
2021 n_bytes = packet_remaining();
2022 tty_parse_modes(s->ttyfd, &n_bytes);
2025 pty_setowner(s->pw, s->tty);
2027 /* Set window size from the packet. */
2028 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
2031 session_proctitle(s);
2036 session_subsystem_req(Session *s)
2041 char *cmd, *subsys = packet_get_string(&len);
2045 logit("subsystem request for %.100s", subsys);
2047 for (i = 0; i < options.num_subsystems; i++) {
2048 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
2049 cmd = options.subsystem_command[i];
2050 if (stat(cmd, &st) < 0) {
2051 error("subsystem: cannot stat %s: %s", cmd,
2055 debug("subsystem: exec() %s", cmd);
2056 s->is_subsystem = 1;
2064 logit("subsystem request for %.100s failed, subsystem not found",
2072 session_x11_req(Session *s)
2076 if (s->auth_proto != NULL || s->auth_data != NULL) {
2077 error("session_x11_req: session %d: "
2078 "x11 forwarding already active", s->self);
2081 s->single_connection = packet_get_char();
2082 s->auth_proto = packet_get_string(NULL);
2083 s->auth_data = packet_get_string(NULL);
2084 s->screen = packet_get_int();
2087 success = session_setup_x11fwd(s);
2089 xfree(s->auth_proto);
2090 xfree(s->auth_data);
2091 s->auth_proto = NULL;
2092 s->auth_data = NULL;
2098 session_shell_req(Session *s)
2106 session_exec_req(Session *s)
2109 char *command = packet_get_string(&len);
2111 do_exec(s, command);
2117 session_break_req(Session *s)
2120 packet_get_int(); /* ignored */
2123 if (s->ttyfd == -1 ||
2124 tcsendbreak(s->ttyfd, 0) < 0)
2130 session_env_req(Session *s)
2133 u_int name_len, val_len, i;
2135 name = packet_get_string(&name_len);
2136 val = packet_get_string(&val_len);
2139 /* Don't set too many environment variables */
2140 if (s->num_env > 128) {
2141 debug2("Ignoring env request %s: too many env vars", name);
2145 for (i = 0; i < options.num_accept_env; i++) {
2146 if (match_pattern(name, options.accept_env[i])) {
2147 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2148 s->env = xrealloc(s->env, sizeof(*s->env) *
2150 s->env[s->num_env].name = name;
2151 s->env[s->num_env].val = val;
2156 debug2("Ignoring env request %s: disallowed name", name);
2165 session_auth_agent_req(Session *s)
2167 static int called = 0;
2169 if (no_agent_forwarding_flag) {
2170 debug("session_auth_agent_req: no_agent_forwarding_flag");
2177 return auth_input_request_forwarding(s->pw);
2182 session_input_channel_req(Channel *c, const char *rtype)
2187 if ((s = session_by_channel(c->self)) == NULL) {
2188 logit("session_input_channel_req: no session %d req %.100s",
2192 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2195 * a session is in LARVAL state until a shell, a command
2196 * or a subsystem is executed
2198 if (c->type == SSH_CHANNEL_LARVAL) {
2199 if (strcmp(rtype, "shell") == 0) {
2200 success = session_shell_req(s);
2201 } else if (strcmp(rtype, "exec") == 0) {
2202 success = session_exec_req(s);
2203 } else if (strcmp(rtype, "pty-req") == 0) {
2204 success = session_pty_req(s);
2205 } else if (strcmp(rtype, "x11-req") == 0) {
2206 success = session_x11_req(s);
2207 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2208 success = session_auth_agent_req(s);
2209 } else if (strcmp(rtype, "subsystem") == 0) {
2210 success = session_subsystem_req(s);
2211 } else if (strcmp(rtype, "env") == 0) {
2212 success = session_env_req(s);
2215 if (strcmp(rtype, "window-change") == 0) {
2216 success = session_window_change_req(s);
2217 } else if (strcmp(rtype, "break") == 0) {
2218 success = session_break_req(s);
2225 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2228 fatal("session_set_fds: called for proto != 2.0");
2230 * now that have a child and a pipe to the child,
2231 * we can activate our channel and register the fd's
2233 if (s->chanid == -1)
2234 fatal("no channel for session %d", s->self);
2235 channel_set_fds(s->chanid,
2237 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2239 CHAN_SES_WINDOW_DEFAULT);
2243 * Function to perform pty cleanup. Also called if we get aborted abnormally
2244 * (e.g., due to a dropped connection).
2247 session_pty_cleanup2(Session *s)
2250 error("session_pty_cleanup: no session");
2256 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2258 /* Record that the user has logged out. */
2260 record_logout(s->pid, s->tty, s->pw->pw_name);
2262 /* Release the pseudo-tty. */
2264 pty_release(s->tty);
2267 * Close the server side of the socket pairs. We must do this after
2268 * the pty cleanup, so that another process doesn't get this pty
2269 * while we're still cleaning up.
2271 if (close(s->ptymaster) < 0)
2272 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2274 /* unlink pty from session */
2279 session_pty_cleanup(Session *s)
2281 PRIVSEP(session_pty_cleanup2(s));
2287 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2302 return "SIG@openssh.com";
2306 session_close_x11(int id)
2310 if ((c = channel_by_id(id)) == NULL) {
2311 debug("session_close_x11: x11 channel %d missing", id);
2313 /* Detach X11 listener */
2314 debug("session_close_x11: detach x11 channel %d", id);
2315 channel_cancel_cleanup(id);
2316 if (c->ostate != CHAN_OUTPUT_CLOSED)
2322 session_close_single_x11(int id, void *arg)
2327 debug3("session_close_single_x11: channel %d", id);
2328 channel_cancel_cleanup(id);
2329 if ((s = session_by_x11_channel(id)) == NULL)
2330 fatal("session_close_single_x11: no x11 channel %d", id);
2331 for (i = 0; s->x11_chanids[i] != -1; i++) {
2332 debug("session_close_single_x11: session %d: "
2333 "closing channel %d", s->self, s->x11_chanids[i]);
2335 * The channel "id" is already closing, but make sure we
2336 * close all of its siblings.
2338 if (s->x11_chanids[i] != id)
2339 session_close_x11(s->x11_chanids[i]);
2341 xfree(s->x11_chanids);
2342 s->x11_chanids = NULL;
2347 if (s->auth_proto) {
2348 xfree(s->auth_proto);
2349 s->auth_proto = NULL;
2352 xfree(s->auth_data);
2353 s->auth_data = NULL;
2355 if (s->auth_display) {
2356 xfree(s->auth_display);
2357 s->auth_display = NULL;
2362 session_exit_message(Session *s, int status)
2366 if ((c = channel_lookup(s->chanid)) == NULL)
2367 fatal("session_exit_message: session %d: no channel %d",
2368 s->self, s->chanid);
2369 debug("session_exit_message: session %d channel %d pid %ld",
2370 s->self, s->chanid, (long)s->pid);
2372 if (WIFEXITED(status)) {
2373 channel_request_start(s->chanid, "exit-status", 0);
2374 packet_put_int(WEXITSTATUS(status));
2376 } else if (WIFSIGNALED(status)) {
2377 channel_request_start(s->chanid, "exit-signal", 0);
2378 packet_put_cstring(sig2name(WTERMSIG(status)));
2380 packet_put_char(WCOREDUMP(status));
2381 #else /* WCOREDUMP */
2383 #endif /* WCOREDUMP */
2384 packet_put_cstring("");
2385 packet_put_cstring("");
2388 /* Some weird exit cause. Just exit. */
2389 packet_disconnect("wait returned status %04x.", status);
2392 /* disconnect channel */
2393 debug("session_exit_message: release channel %d", s->chanid);
2396 * Adjust cleanup callback attachment to send close messages when
2397 * the channel gets EOF. The session will be then be closed
2398 * by session_close_by_channel when the childs close their fds.
2400 channel_register_cleanup(c->self, session_close_by_channel, 1);
2403 * emulate a write failure with 'chan_write_failed', nobody will be
2404 * interested in data we write.
2405 * Note that we must not call 'chan_read_failed', since there could
2406 * be some more data waiting in the pipe.
2408 if (c->ostate != CHAN_OUTPUT_CLOSED)
2409 chan_write_failed(c);
2413 session_close(Session *s)
2417 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2419 session_pty_cleanup(s);
2425 xfree(s->x11_chanids);
2426 if (s->auth_display)
2427 xfree(s->auth_display);
2429 xfree(s->auth_data);
2431 xfree(s->auth_proto);
2433 for (i = 0; i < s->num_env; i++) {
2434 xfree(s->env[i].name);
2435 xfree(s->env[i].val);
2439 session_proctitle(s);
2443 session_close_by_pid(pid_t pid, int status)
2445 Session *s = session_by_pid(pid);
2447 debug("session_close_by_pid: no session for pid %ld",
2451 if (s->chanid != -1)
2452 session_exit_message(s, status);
2454 session_pty_cleanup(s);
2459 * this is called when a channel dies before
2460 * the session 'child' itself dies
2463 session_close_by_channel(int id, void *arg)
2465 Session *s = session_by_channel(id);
2469 debug("session_close_by_channel: no session for id %d", id);
2472 debug("session_close_by_channel: channel %d child %ld",
2475 debug("session_close_by_channel: channel %d: has child", id);
2477 * delay detach of session, but release pty, since
2478 * the fd's to the child are already closed
2481 session_pty_cleanup(s);
2484 /* detach by removing callback */
2485 channel_cancel_cleanup(s->chanid);
2487 /* Close any X11 listeners associated with this session */
2488 if (s->x11_chanids != NULL) {
2489 for (i = 0; s->x11_chanids[i] != -1; i++) {
2490 session_close_x11(s->x11_chanids[i]);
2491 s->x11_chanids[i] = -1;
2500 session_destroy_all(void (*closefunc)(Session *))
2503 for (i = 0; i < MAX_SESSIONS; i++) {
2504 Session *s = &sessions[i];
2506 if (closefunc != NULL)
2515 session_tty_list(void)
2517 static char buf[1024];
2522 for (i = 0; i < MAX_SESSIONS; i++) {
2523 Session *s = &sessions[i];
2524 if (s->used && s->ttyfd != -1) {
2526 if (strncmp(s->tty, "/dev/", 5) != 0) {
2527 cp = strrchr(s->tty, '/');
2528 cp = (cp == NULL) ? s->tty : cp + 1;
2533 strlcat(buf, ",", sizeof buf);
2534 strlcat(buf, cp, sizeof buf);
2538 strlcpy(buf, "notty", sizeof buf);
2543 session_proctitle(Session *s)
2546 error("no user for session %d", s->self);
2548 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2552 session_setup_x11fwd(Session *s)
2555 char display[512], auth_display[512];
2556 char hostname[MAXHOSTNAMELEN];
2559 if (no_x11_forwarding_flag) {
2560 packet_send_debug("X11 forwarding disabled in user configuration file.");
2563 if (!options.x11_forwarding) {
2564 debug("X11 forwarding disabled in server configuration file.");
2567 if (!options.xauth_location ||
2568 (stat(options.xauth_location, &st) == -1)) {
2569 packet_send_debug("No xauth program; cannot forward with spoofing.");
2572 if (options.use_login) {
2573 packet_send_debug("X11 forwarding disabled; "
2574 "not compatible with UseLogin=yes.");
2577 if (s->display != NULL) {
2578 debug("X11 display already set.");
2581 if (x11_create_display_inet(options.x11_display_offset,
2582 options.x11_use_localhost, s->single_connection,
2583 &s->display_number, &s->x11_chanids) == -1) {
2584 debug("x11_create_display_inet failed.");
2587 for (i = 0; s->x11_chanids[i] != -1; i++) {
2588 channel_register_cleanup(s->x11_chanids[i],
2589 session_close_single_x11, 0);
2592 /* Set up a suitable value for the DISPLAY variable. */
2593 if (gethostname(hostname, sizeof(hostname)) < 0)
2594 fatal("gethostname: %.100s", strerror(errno));
2596 * auth_display must be used as the displayname when the
2597 * authorization entry is added with xauth(1). This will be
2598 * different than the DISPLAY string for localhost displays.
2600 if (options.x11_use_localhost) {
2601 snprintf(display, sizeof display, "localhost:%u.%u",
2602 s->display_number, s->screen);
2603 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2604 s->display_number, s->screen);
2605 s->display = xstrdup(display);
2606 s->auth_display = xstrdup(auth_display);
2608 #ifdef IPADDR_IN_DISPLAY
2610 struct in_addr my_addr;
2612 he = gethostbyname(hostname);
2614 error("Can't get IP address for X11 DISPLAY.");
2615 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2618 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2619 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2620 s->display_number, s->screen);
2622 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2623 s->display_number, s->screen);
2625 s->display = xstrdup(display);
2626 s->auth_display = xstrdup(display);
2633 do_authenticated2(Authctxt *authctxt)
2635 server_loop2(authctxt);
2639 do_cleanup(Authctxt *authctxt)
2641 static int called = 0;
2643 debug("do_cleanup");
2645 /* no cleanup if we're in the child for login shell */
2649 /* avoid double cleanup */
2654 if (authctxt == NULL)
2657 if (options.kerberos_ticket_cleanup &&
2659 krb5_cleanup_proc(authctxt);
2663 if (compat20 && options.gss_cleanup_creds)
2664 ssh_gssapi_cleanup_creds();
2668 if (options.use_pam) {
2670 sshpam_thread_cleanup();
2674 /* remove agent socket */
2675 auth_sock_cleanup_proc(authctxt->pw);
2678 * Cleanup ptys/utmp only if privsep is disabled,
2679 * or if running in monitor.
2681 if (!use_privsep || mm_is_monitor())
2682 session_destroy_all(session_pty_cleanup2);