1 /* $OpenBSD: session.c,v 1.258 2010/11/25 04:10:09 djm Exp $ */
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * As far as I am concerned, the code I have written for this software
7 * can be used freely for any purpose. Any derived versions of this
8 * software must be clearly marked as such, and if the derived work is
9 * incompatible with the protocol description in the RFC file, it must be
10 * called by a name other than "ssh" or "Secure Shell".
12 * SSH2 support by Markus Friedl.
13 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
24 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #ifdef HAVE_SYS_STAT_H
41 # include <sys/stat.h>
43 #include <sys/socket.h>
47 #include <arpa/inet.h>
63 #include "openbsd-compat/sys-queue.h"
82 #include "auth-options.h"
83 #include "pathnames.h"
87 #include "serverloop.h"
92 #include "monitor_wrap.h"
95 #if defined(KRB5) && defined(USE_AFS)
99 #define IS_INTERNAL_SFTP(c) \
100 (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
101 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
102 c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
103 c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
107 Session *session_new(void);
108 void session_set_fds(Session *, int, int, int, int, int);
109 void session_pty_cleanup(Session *);
110 void session_proctitle(Session *);
111 int session_setup_x11fwd(Session *);
112 int do_exec_pty(Session *, const char *);
113 int do_exec_no_pty(Session *, const char *);
114 int do_exec(Session *, const char *);
115 void do_login(Session *, const char *);
116 #ifdef LOGIN_NEEDS_UTMPX
117 static void do_pre_login(Session *s);
119 void do_child(Session *, const char *);
121 int check_quietlogin(Session *, const char *);
123 static void do_authenticated1(Authctxt *);
124 static void do_authenticated2(Authctxt *);
126 static int session_pty_req(Session *);
129 extern ServerOptions options;
130 extern char *__progname;
131 extern int log_stderr;
132 extern int debug_flag;
133 extern u_int utmp_len;
134 extern int startup_pipe;
135 extern void destroy_sensitive_data(void);
136 extern Buffer loginmsg;
138 /* original command from peer. */
139 const char *original_command = NULL;
142 static int sessions_first_unused = -1;
143 static int sessions_nalloc = 0;
144 static Session *sessions = NULL;
146 #define SUBSYSTEM_NONE 0
147 #define SUBSYSTEM_EXT 1
148 #define SUBSYSTEM_INT_SFTP 2
149 #define SUBSYSTEM_INT_SFTP_ERROR 3
151 #ifdef HAVE_LOGIN_CAP
155 static int is_child = 0;
157 /* Name and directory of socket for authentication agent forwarding. */
158 static char *auth_sock_name = NULL;
159 static char *auth_sock_dir = NULL;
161 /* removes the agent forwarding socket */
164 auth_sock_cleanup_proc(struct passwd *pw)
166 if (auth_sock_name != NULL) {
167 temporarily_use_uid(pw);
168 unlink(auth_sock_name);
169 rmdir(auth_sock_dir);
170 auth_sock_name = NULL;
176 auth_input_request_forwarding(struct passwd * pw)
180 struct sockaddr_un sunaddr;
182 if (auth_sock_name != NULL) {
183 error("authentication forwarding requested twice.");
187 /* Temporarily drop privileged uid for mkdir/bind. */
188 temporarily_use_uid(pw);
190 /* Allocate a buffer for the socket name, and format the name. */
191 auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
193 /* Create private directory for socket */
194 if (mkdtemp(auth_sock_dir) == NULL) {
195 packet_send_debug("Agent forwarding disabled: "
196 "mkdtemp() failed: %.100s", strerror(errno));
198 xfree(auth_sock_dir);
199 auth_sock_dir = NULL;
203 xasprintf(&auth_sock_name, "%s/agent.%ld",
204 auth_sock_dir, (long) getpid());
206 /* Create the socket. */
207 sock = socket(AF_UNIX, SOCK_STREAM, 0);
209 error("socket: %.100s", strerror(errno));
214 /* Bind it to the name. */
215 memset(&sunaddr, 0, sizeof(sunaddr));
216 sunaddr.sun_family = AF_UNIX;
217 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
219 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
220 error("bind: %.100s", strerror(errno));
225 /* Restore the privileged uid. */
228 /* Start listening on the socket. */
229 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
230 error("listen: %.100s", strerror(errno));
234 /* Allocate a channel for the authentication agent socket. */
235 /* this shouldn't matter if its hpn or not - cjr */
236 nc = channel_new("auth socket",
237 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
238 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
239 0, "auth socket", 1);
240 nc->path = xstrdup(auth_sock_name);
244 if (auth_sock_name != NULL)
245 xfree(auth_sock_name);
246 if (auth_sock_dir != NULL) {
247 rmdir(auth_sock_dir);
248 xfree(auth_sock_dir);
252 auth_sock_name = NULL;
253 auth_sock_dir = NULL;
258 display_loginmsg(void)
260 if (buffer_len(&loginmsg) > 0) {
261 buffer_append(&loginmsg, "\0", 1);
262 printf("%s", (char *)buffer_ptr(&loginmsg));
263 buffer_clear(&loginmsg);
268 do_authenticated(Authctxt *authctxt)
270 setproctitle("%s", authctxt->pw->pw_name);
272 /* setup the channel layer */
273 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
274 channel_permit_all_opens();
279 do_authenticated2(authctxt);
281 do_authenticated1(authctxt);
283 do_cleanup(authctxt);
287 * Prepares for an interactive session. This is called after the user has
288 * been successfully authenticated. During this message exchange, pseudo
289 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
290 * are requested, etc.
293 do_authenticated1(Authctxt *authctxt)
297 int success, type, screen_flag;
298 int enable_compression_after_reply = 0;
299 u_int proto_len, data_len, dlen, compression_level = 0;
303 error("no more sessions");
306 s->authctxt = authctxt;
307 s->pw = authctxt->pw;
310 * We stay in this loop until the client requests to execute a shell
316 /* Get a packet from the client. */
317 type = packet_read();
319 /* Process the packet. */
321 case SSH_CMSG_REQUEST_COMPRESSION:
322 compression_level = packet_get_int();
324 if (compression_level < 1 || compression_level > 9) {
325 packet_send_debug("Received invalid compression level %d.",
329 if (options.compression == COMP_NONE) {
330 debug2("compression disabled");
333 /* Enable compression after we have responded with SUCCESS. */
334 enable_compression_after_reply = 1;
338 case SSH_CMSG_REQUEST_PTY:
339 success = session_pty_req(s);
342 case SSH_CMSG_X11_REQUEST_FORWARDING:
343 s->auth_proto = packet_get_string(&proto_len);
344 s->auth_data = packet_get_string(&data_len);
346 screen_flag = packet_get_protocol_flags() &
347 SSH_PROTOFLAG_SCREEN_NUMBER;
348 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
350 if (packet_remaining() == 4) {
352 debug2("Buggy client: "
353 "X11 screen flag missing");
354 s->screen = packet_get_int();
359 success = session_setup_x11fwd(s);
361 xfree(s->auth_proto);
363 s->auth_proto = NULL;
368 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
369 if (!options.allow_agent_forwarding ||
370 no_agent_forwarding_flag || compat13) {
371 debug("Authentication agent forwarding not permitted for this authentication.");
374 debug("Received authentication agent forwarding request.");
375 success = auth_input_request_forwarding(s->pw);
378 case SSH_CMSG_PORT_FORWARD_REQUEST:
379 if (no_port_forwarding_flag) {
380 debug("Port forwarding not permitted for this authentication.");
383 if (!options.allow_tcp_forwarding) {
384 debug("Port forwarding not permitted.");
387 debug("Received TCP/IP port forwarding request.");
388 if (channel_input_port_forward_request(s->pw->pw_uid == 0,
389 options.gateway_ports) < 0) {
390 debug("Port forwarding failed.");
396 case SSH_CMSG_MAX_PACKET_SIZE:
397 if (packet_set_maxsize(packet_get_int()) > 0)
401 case SSH_CMSG_EXEC_SHELL:
402 case SSH_CMSG_EXEC_CMD:
403 if (type == SSH_CMSG_EXEC_CMD) {
404 command = packet_get_string(&dlen);
405 debug("Exec command '%.500s'", command);
406 if (do_exec(s, command) != 0)
408 "command execution failed");
411 if (do_exec(s, NULL) != 0)
413 "shell execution failed");
421 * Any unknown messages in this phase are ignored,
422 * and a failure message is returned.
424 logit("Unknown packet type received after authentication: %d", type);
426 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
430 /* Enable compression now that we have replied if appropriate. */
431 if (enable_compression_after_reply) {
432 enable_compression_after_reply = 0;
433 packet_start_compression(compression_level);
440 * This is called to fork and execute a command when we have no tty. This
441 * will call do_child from the child, and server_loop from the parent after
442 * setting up file descriptors and such.
445 do_exec_no_pty(Session *s, const char *command)
450 int pin[2], pout[2], perr[2];
453 fatal("do_exec_no_pty: no session");
455 /* Allocate pipes for communicating with the program. */
457 error("%s: pipe in: %.100s", __func__, strerror(errno));
460 if (pipe(pout) < 0) {
461 error("%s: pipe out: %.100s", __func__, strerror(errno));
466 if (pipe(perr) < 0) {
467 error("%s: pipe err: %.100s", __func__,
476 int inout[2], err[2];
479 fatal("do_exec_no_pty: no session");
481 /* Uses socket pairs to communicate with the program. */
482 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) {
483 error("%s: socketpair #1: %.100s", __func__, strerror(errno));
486 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) {
487 error("%s: socketpair #2: %.100s", __func__,
495 session_proctitle(s);
497 /* Fork the child. */
498 switch ((pid = fork())) {
500 error("%s: fork: %.100s", __func__, strerror(errno));
518 /* Child. Reinitialize the log since the pid has changed. */
519 log_init(__progname, options.log_level,
520 options.log_facility, log_stderr);
523 * Create a new session and process group since the 4.4BSD
524 * setlogin() affects the entire process group.
527 error("setsid failed: %.100s", strerror(errno));
531 * Redirect stdin. We close the parent side of the socket
532 * pair, and make the child side the standard input.
535 if (dup2(pin[0], 0) < 0)
536 perror("dup2 stdin");
539 /* Redirect stdout. */
541 if (dup2(pout[1], 1) < 0)
542 perror("dup2 stdout");
545 /* Redirect stderr. */
547 if (dup2(perr[1], 2) < 0)
548 perror("dup2 stderr");
552 * Redirect stdin, stdout, and stderr. Stdin and stdout will
553 * use the same socket, as some programs (particularly rdist)
554 * seem to depend on it.
558 if (dup2(inout[0], 0) < 0) /* stdin */
559 perror("dup2 stdin");
560 if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */
561 perror("dup2 stdout");
563 if (dup2(err[0], 2) < 0) /* stderr */
564 perror("dup2 stderr");
570 cray_init_job(s->pw); /* set up cray jid and tmpdir */
573 /* Do processing for the child (exec command etc). */
574 do_child(s, command);
581 signal(WJSIGNAL, cray_job_termination_handler);
584 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
588 /* Set interactive/non-interactive mode. */
589 packet_set_interactive(s->display != NULL,
590 options.ip_qos_interactive, options.ip_qos_bulk);
593 * Clear loginmsg, since it's the child's responsibility to display
594 * it to the user, otherwise multiple sessions may accumulate
595 * multiple copies of the login messages.
597 buffer_clear(&loginmsg);
600 /* We are the parent. Close the child sides of the pipes. */
606 session_set_fds(s, pin[1], pout[0], perr[0],
609 /* Enter the interactive session. */
610 server_loop(pid, pin[1], pout[0], perr[0]);
611 /* server_loop has closed pin[1], pout[0], and perr[0]. */
614 /* We are the parent. Close the child sides of the socket pairs. */
619 * Enter the interactive session. Note: server_loop must be able to
620 * handle the case that fdin and fdout are the same.
623 session_set_fds(s, inout[1], inout[1], err[1],
626 server_loop(pid, inout[1], inout[1], err[1]);
627 /* server_loop has closed inout[1] and err[1]. */
634 * This is called to fork and execute a command when we have a tty. This
635 * will call do_child from the child, and server_loop from the parent after
636 * setting up file descriptors, controlling tty, updating wtmp, utmp,
637 * lastlog, and other such operations.
640 do_exec_pty(Session *s, const char *command)
642 int fdout, ptyfd, ttyfd, ptymaster;
646 fatal("do_exec_pty: no session");
651 * Create another descriptor of the pty master side for use as the
652 * standard input. We could use the original descriptor, but this
653 * simplifies code in server_loop. The descriptor is bidirectional.
654 * Do this before forking (and cleanup in the child) so as to
655 * detect and gracefully fail out-of-fd conditions.
657 if ((fdout = dup(ptyfd)) < 0) {
658 error("%s: dup #1: %s", __func__, strerror(errno));
663 /* we keep a reference to the pty master */
664 if ((ptymaster = dup(ptyfd)) < 0) {
665 error("%s: dup #2: %s", __func__, strerror(errno));
672 /* Fork the child. */
673 switch ((pid = fork())) {
675 error("%s: fork: %.100s", __func__, strerror(errno));
687 /* Child. Reinitialize the log because the pid has changed. */
688 log_init(__progname, options.log_level,
689 options.log_facility, log_stderr);
690 /* Close the master side of the pseudo tty. */
693 /* Make the pseudo tty our controlling tty. */
694 pty_make_controlling_tty(&ttyfd, s->tty);
696 /* Redirect stdin/stdout/stderr from the pseudo tty. */
697 if (dup2(ttyfd, 0) < 0)
698 error("dup2 stdin: %s", strerror(errno));
699 if (dup2(ttyfd, 1) < 0)
700 error("dup2 stdout: %s", strerror(errno));
701 if (dup2(ttyfd, 2) < 0)
702 error("dup2 stderr: %s", strerror(errno));
704 /* Close the extra descriptor for the pseudo tty. */
707 /* record login, etc. similar to login(1) */
709 if (!(options.use_login && command == NULL)) {
711 cray_init_job(s->pw); /* set up cray jid and tmpdir */
713 do_login(s, command);
715 # ifdef LOGIN_NEEDS_UTMPX
721 * Do common processing for the child, such as execing
724 do_child(s, command);
731 signal(WJSIGNAL, cray_job_termination_handler);
734 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
739 /* Parent. Close the slave side of the pseudo tty. */
742 /* Enter interactive session. */
743 s->ptymaster = ptymaster;
744 packet_set_interactive(1,
745 options.ip_qos_interactive, options.ip_qos_bulk);
747 session_set_fds(s, ptyfd, fdout, -1, 1, 1);
749 server_loop(pid, ptyfd, fdout, -1);
750 /* server_loop _has_ closed ptyfd and fdout. */
755 #ifdef LOGIN_NEEDS_UTMPX
757 do_pre_login(Session *s)
760 struct sockaddr_storage from;
761 pid_t pid = getpid();
764 * Get IP address of client. If the connection is not a socket, let
765 * the address be 0.0.0.0.
767 memset(&from, 0, sizeof(from));
768 fromlen = sizeof(from);
769 if (packet_connection_is_on_socket()) {
770 if (getpeername(packet_get_connection_in(),
771 (struct sockaddr *)&from, &fromlen) < 0) {
772 debug("getpeername: %.100s", strerror(errno));
777 record_utmp_only(pid, s->tty, s->pw->pw_name,
778 get_remote_name_or_ip(utmp_len, options.use_dns),
779 (struct sockaddr *)&from, fromlen);
784 * This is called to fork and execute a command. If another command is
785 * to be forced, execute that instead.
788 do_exec(Session *s, const char *command)
792 if (options.adm_forced_command) {
793 original_command = command;
794 command = options.adm_forced_command;
795 if (IS_INTERNAL_SFTP(command)) {
796 s->is_subsystem = s->is_subsystem ?
797 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
798 } else if (s->is_subsystem)
799 s->is_subsystem = SUBSYSTEM_EXT;
800 debug("Forced command (config) '%.900s'", command);
801 } else if (forced_command) {
802 original_command = command;
803 command = forced_command;
804 if (IS_INTERNAL_SFTP(command)) {
805 s->is_subsystem = s->is_subsystem ?
806 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
807 } else if (s->is_subsystem)
808 s->is_subsystem = SUBSYSTEM_EXT;
809 debug("Forced command (key option) '%.900s'", command);
812 #ifdef SSH_AUDIT_EVENTS
814 PRIVSEP(audit_run_command(command));
815 else if (s->ttyfd == -1) {
816 char *shell = s->pw->pw_shell;
818 if (shell[0] == '\0') /* empty shell means /bin/sh */
820 PRIVSEP(audit_run_command(shell));
824 ret = do_exec_pty(s, command);
826 ret = do_exec_no_pty(s, command);
828 original_command = NULL;
831 * Clear loginmsg: it's the child's responsibility to display
832 * it to the user, otherwise multiple sessions may accumulate
833 * multiple copies of the login messages.
835 buffer_clear(&loginmsg);
840 /* administrative, login(1)-like work */
842 do_login(Session *s, const char *command)
845 struct sockaddr_storage from;
846 struct passwd * pw = s->pw;
847 pid_t pid = getpid();
850 * Get IP address of client. If the connection is not a socket, let
851 * the address be 0.0.0.0.
853 memset(&from, 0, sizeof(from));
854 fromlen = sizeof(from);
855 if (packet_connection_is_on_socket()) {
856 if (getpeername(packet_get_connection_in(),
857 (struct sockaddr *)&from, &fromlen) < 0) {
858 debug("getpeername: %.100s", strerror(errno));
863 /* Record that there was a login on that tty from the remote host. */
865 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
866 get_remote_name_or_ip(utmp_len,
868 (struct sockaddr *)&from, fromlen);
872 * If password change is needed, do it now.
873 * This needs to occur before the ~/.hushlogin check.
875 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
878 s->authctxt->force_pwchange = 0;
879 /* XXX - signal [net] parent to enable forwardings */
883 if (check_quietlogin(s, command))
892 * Display the message of the day.
899 #ifdef HAVE_LOGIN_CAP
903 #ifdef HAVE_LOGIN_CAP
904 fname = login_getcapstr(lc, "copyright", NULL, NULL);
905 if (fname != NULL && (f = fopen(fname, "r")) != NULL) {
906 while (fgets(buf, sizeof(buf), f) != NULL)
910 #endif /* HAVE_LOGIN_CAP */
911 (void)printf("%s\n\t%s %s\n",
912 "Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
913 "The Regents of the University of California. ",
914 "All rights reserved.");
918 if (options.print_motd) {
919 #ifdef HAVE_LOGIN_CAP
920 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
923 f = fopen("/etc/motd", "r");
926 while (fgets(buf, sizeof(buf), f))
935 * Check for quiet login, either .hushlogin or command given.
938 check_quietlogin(Session *s, const char *command)
941 struct passwd *pw = s->pw;
944 /* Return 1 if .hushlogin exists or a command given. */
947 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
948 #ifdef HAVE_LOGIN_CAP
949 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
952 if (stat(buf, &st) >= 0)
959 * Sets the value of the given variable in the environment. If the variable
960 * already exists, its value is overridden.
963 child_set_env(char ***envp, u_int *envsizep, const char *name,
971 * If we're passed an uninitialized list, allocate a single null
972 * entry before continuing.
974 if (*envp == NULL && *envsizep == 0) {
975 *envp = xmalloc(sizeof(char *));
981 * Find the slot where the value should be stored. If the variable
982 * already exists, we reuse the slot; otherwise we append a new slot
983 * at the end of the array, expanding if necessary.
986 namelen = strlen(name);
987 for (i = 0; env[i]; i++)
988 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
991 /* Reuse the slot. */
994 /* New variable. Expand if necessary. */
996 if (i >= envsize - 1) {
998 fatal("child_set_env: too many env vars");
1000 env = (*envp) = xrealloc(env, envsize, sizeof(char *));
1001 *envsizep = envsize;
1003 /* Need to set the NULL pointer at end of array beyond the new slot. */
1007 /* Allocate space and format the variable in the appropriate slot. */
1008 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1009 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1013 * Reads environment variables from the given file and adds/overrides them
1014 * into the environment. If the file does not exist, this does nothing.
1015 * Otherwise, it must consist of empty lines, comments (line starts with '#')
1016 * and assignments of the form name=value. No other forms are allowed.
1019 read_environment_file(char ***env, u_int *envsize,
1020 const char *filename)
1027 f = fopen(filename, "r");
1031 while (fgets(buf, sizeof(buf), f)) {
1032 if (++lineno > 1000)
1033 fatal("Too many lines in environment file %s", filename);
1034 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
1036 if (!*cp || *cp == '#' || *cp == '\n')
1039 cp[strcspn(cp, "\n")] = '\0';
1041 value = strchr(cp, '=');
1042 if (value == NULL) {
1043 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
1048 * Replace the equals sign by nul, and advance value to
1053 child_set_env(env, envsize, cp, value);
1058 #ifdef HAVE_ETC_DEFAULT_LOGIN
1060 * Return named variable from specified environment, or NULL if not present.
1063 child_get_env(char **env, const char *name)
1069 for (i=0; env[i] != NULL; i++)
1070 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
1071 return(env[i] + len + 1);
1076 * Read /etc/default/login.
1077 * We pick up the PATH (or SUPATH for root) and UMASK.
1080 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
1082 char **tmpenv = NULL, *var;
1083 u_int i, tmpenvsize = 0;
1087 * We don't want to copy the whole file to the child's environment,
1088 * so we use a temporary environment and copy the variables we're
1091 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
1097 var = child_get_env(tmpenv, "SUPATH");
1099 var = child_get_env(tmpenv, "PATH");
1101 child_set_env(env, envsize, "PATH", var);
1103 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
1104 if (sscanf(var, "%5lo", &mask) == 1)
1105 umask((mode_t)mask);
1107 for (i = 0; tmpenv[i] != NULL; i++)
1111 #endif /* HAVE_ETC_DEFAULT_LOGIN */
1114 copy_environment(char **source, char ***env, u_int *envsize)
1116 char *var_name, *var_val;
1122 for(i = 0; source[i] != NULL; i++) {
1123 var_name = xstrdup(source[i]);
1124 if ((var_val = strstr(var_name, "=")) == NULL) {
1130 debug3("Copy environment: %s=%s", var_name, var_val);
1131 child_set_env(env, envsize, var_name, var_val);
1138 do_setup_env(Session *s, const char *shell)
1143 struct passwd *pw = s->pw;
1144 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
1147 extern char **environ;
1154 /* Initialize the environment. */
1156 env = xcalloc(envsize, sizeof(char *));
1161 * The Windows environment contains some setting which are
1162 * important for a running system. They must not be dropped.
1167 p = fetch_windows_environment();
1168 copy_environment(p, &env, &envsize);
1169 free_windows_environment(p);
1174 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1177 /* Allow any GSSAPI methods that we've used to alter
1178 * the childs environment as they see fit
1180 ssh_gssapi_do_child(&env, &envsize);
1183 if (!options.use_login) {
1184 /* Set basic environment. */
1185 for (i = 0; i < s->num_env; i++)
1186 child_set_env(&env, &envsize, s->env[i].name,
1189 child_set_env(&env, &envsize, "USER", pw->pw_name);
1190 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1192 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1194 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1195 snprintf(buf, sizeof buf, "%.200s/%.50s",
1196 _PATH_MAILDIR, pw->pw_name);
1197 child_set_env(&env, &envsize, "MAIL", buf);
1198 #ifdef HAVE_LOGIN_CAP
1199 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1200 child_set_env(&env, &envsize, "TERM", "su");
1202 environ = xmalloc(sizeof(char *));
1204 (void) setusercontext(lc, pw, pw->pw_uid,
1205 LOGIN_SETENV|LOGIN_SETPATH);
1206 copy_environment(environ, &env, &envsize);
1209 * This interferes with libc's management of the environment
1210 * in horrible ways that can cause sshd to crash.
1212 for (var = environ; *var != NULL; ++var)
1217 #else /* HAVE_LOGIN_CAP */
1218 # ifndef HAVE_CYGWIN
1220 * There's no standard path on Windows. The path contains
1221 * important components pointing to the system directories,
1222 * needed for loading shared libraries. So the path better
1223 * remains intact here.
1225 # ifdef HAVE_ETC_DEFAULT_LOGIN
1226 read_etc_default_login(&env, &envsize, pw->pw_uid);
1227 path = child_get_env(env, "PATH");
1228 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1229 if (path == NULL || *path == '\0') {
1230 child_set_env(&env, &envsize, "PATH",
1231 s->pw->pw_uid == 0 ?
1232 SUPERUSER_PATH : _PATH_STDPATH);
1234 # endif /* HAVE_CYGWIN */
1235 #endif /* HAVE_LOGIN_CAP */
1237 /* Normal systems set SHELL by default. */
1238 child_set_env(&env, &envsize, "SHELL", shell);
1241 /* Set custom environment options from RSA authentication. */
1242 if (!options.use_login) {
1243 while (custom_environment) {
1244 struct envstring *ce = custom_environment;
1247 for (i = 0; str[i] != '=' && str[i]; i++)
1249 if (str[i] == '=') {
1251 child_set_env(&env, &envsize, str, str + i + 1);
1253 custom_environment = ce->next;
1259 /* SSH_CLIENT deprecated */
1260 snprintf(buf, sizeof buf, "%.50s %d %d",
1261 get_remote_ipaddr(), get_remote_port(), get_local_port());
1262 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1264 laddr = get_local_ipaddr(packet_get_connection_in());
1265 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1266 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1268 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1271 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1273 child_set_env(&env, &envsize, "TERM", s->term);
1275 child_set_env(&env, &envsize, "DISPLAY", s->display);
1276 if (original_command)
1277 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1281 if (cray_tmpdir[0] != '\0')
1282 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1283 #endif /* _UNICOS */
1286 * Since we clear KRB5CCNAME at startup, if it's set now then it
1287 * must have been set by a native authentication method (eg AIX or
1288 * SIA), so copy it to the child.
1293 if ((cp = getenv("KRB5CCNAME")) != NULL)
1294 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1301 if ((cp = getenv("AUTHSTATE")) != NULL)
1302 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1303 read_environment_file(&env, &envsize, "/etc/environment");
1307 if (s->authctxt->krb5_ccname)
1308 child_set_env(&env, &envsize, "KRB5CCNAME",
1309 s->authctxt->krb5_ccname);
1313 * Pull in any environment variables that may have
1316 if (options.use_pam) {
1319 p = fetch_pam_child_environment();
1320 copy_environment(p, &env, &envsize);
1321 free_pam_environment(p);
1323 p = fetch_pam_environment();
1324 copy_environment(p, &env, &envsize);
1325 free_pam_environment(p);
1327 #endif /* USE_PAM */
1329 if (auth_sock_name != NULL)
1330 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1333 /* read $HOME/.ssh/environment. */
1334 if (options.permit_user_env && !options.use_login) {
1335 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1336 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1337 read_environment_file(&env, &envsize, buf);
1340 /* dump the environment */
1341 fprintf(stderr, "Environment:\n");
1342 for (i = 0; env[i]; i++)
1343 fprintf(stderr, " %.200s\n", env[i]);
1349 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1350 * first in this order).
1353 do_rc_files(Session *s, const char *shell)
1361 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1363 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1364 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1365 !no_user_rc && stat(_PATH_SSH_USER_RC, &st) >= 0) {
1366 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1367 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1369 fprintf(stderr, "Running %s\n", cmd);
1370 f = popen(cmd, "w");
1373 fprintf(f, "%s %s\n", s->auth_proto,
1377 fprintf(stderr, "Could not run %s\n",
1379 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1381 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1382 _PATH_SSH_SYSTEM_RC);
1383 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1386 fprintf(f, "%s %s\n", s->auth_proto,
1390 fprintf(stderr, "Could not run %s\n",
1391 _PATH_SSH_SYSTEM_RC);
1392 } else if (do_xauth && options.xauth_location != NULL) {
1393 /* Add authority data to .Xauthority if appropriate. */
1396 "Running %.500s remove %.100s\n",
1397 options.xauth_location, s->auth_display);
1399 "%.500s add %.100s %.100s %.100s\n",
1400 options.xauth_location, s->auth_display,
1401 s->auth_proto, s->auth_data);
1403 snprintf(cmd, sizeof cmd, "%s -q -",
1404 options.xauth_location);
1405 f = popen(cmd, "w");
1407 fprintf(f, "remove %s\n",
1409 fprintf(f, "add %s %s %s\n",
1410 s->auth_display, s->auth_proto,
1414 fprintf(stderr, "Could not run %s\n",
1421 do_nologin(struct passwd *pw)
1424 char buf[1024], *nl, *def_nl = _PATH_NOLOGIN;
1427 #ifdef HAVE_LOGIN_CAP
1428 if (login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1430 nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1432 if (pw->pw_uid == 0)
1436 if (stat(nl, &sb) == -1) {
1442 /* /etc/nologin exists. Print its contents if we can and exit. */
1443 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1444 if ((f = fopen(nl, "r")) != NULL) {
1445 while (fgets(buf, sizeof(buf), f))
1453 * Chroot into a directory after checking it for safety: all path components
1454 * must be root-owned directories with strict permissions.
1457 safely_chroot(const char *path, uid_t uid)
1460 char component[MAXPATHLEN];
1464 fatal("chroot path does not begin at root");
1465 if (strlen(path) >= sizeof(component))
1466 fatal("chroot path too long");
1469 * Descend the path, checking that each component is a
1470 * root-owned directory with strict permissions.
1472 for (cp = path; cp != NULL;) {
1473 if ((cp = strchr(cp, '/')) == NULL)
1474 strlcpy(component, path, sizeof(component));
1477 memcpy(component, path, cp - path);
1478 component[cp - path] = '\0';
1481 debug3("%s: checking '%s'", __func__, component);
1483 if (stat(component, &st) != 0)
1484 fatal("%s: stat(\"%s\"): %s", __func__,
1485 component, strerror(errno));
1486 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1487 fatal("bad ownership or modes for chroot "
1488 "directory %s\"%s\"",
1489 cp == NULL ? "" : "component ", component);
1490 if (!S_ISDIR(st.st_mode))
1491 fatal("chroot path %s\"%s\" is not a directory",
1492 cp == NULL ? "" : "component ", component);
1496 if (chdir(path) == -1)
1497 fatal("Unable to chdir to chroot path \"%s\": "
1498 "%s", path, strerror(errno));
1499 if (chroot(path) == -1)
1500 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1501 if (chdir("/") == -1)
1502 fatal("%s: chdir(/) after chroot: %s",
1503 __func__, strerror(errno));
1504 verbose("Changed root directory to \"%s\"", path);
1507 /* Set login name, uid, gid, and groups. */
1509 do_setusercontext(struct passwd *pw)
1511 char *chroot_path, *tmp;
1513 platform_setusercontext(pw);
1515 if (platform_privileged_uidswap()) {
1516 #ifdef HAVE_LOGIN_CAP
1517 if (setusercontext(lc, pw, pw->pw_uid,
1518 (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1519 perror("unable to set user context");
1523 if (setlogin(pw->pw_name) < 0)
1524 error("setlogin failed: %s", strerror(errno));
1525 if (setgid(pw->pw_gid) < 0) {
1529 /* Initialize the group list. */
1530 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1531 perror("initgroups");
1537 platform_setusercontext_post_groups(pw);
1539 if (options.chroot_directory != NULL &&
1540 strcasecmp(options.chroot_directory, "none") != 0) {
1541 tmp = tilde_expand_filename(options.chroot_directory,
1543 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1544 "u", pw->pw_name, (char *)NULL);
1545 safely_chroot(chroot_path, pw->pw_uid);
1550 #ifdef HAVE_LOGIN_CAP
1551 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1552 perror("unable to set user context (setuser)");
1556 /* Permanently switch to the desired uid. */
1557 permanently_set_uid(pw);
1561 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1562 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1566 do_pwchange(Session *s)
1569 fprintf(stderr, "WARNING: Your password has expired.\n");
1570 if (s->ttyfd != -1) {
1572 "You must change your password now and login again!\n");
1573 #ifdef PASSWD_NEEDS_USERNAME
1574 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1577 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1582 "Password change required but no TTY available.\n");
1588 launch_login(struct passwd *pw, const char *hostname)
1590 /* Launch login(1). */
1592 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1593 #ifdef xxxLOGIN_NEEDS_TERM
1594 (s->term ? s->term : "unknown"),
1595 #endif /* LOGIN_NEEDS_TERM */
1596 #ifdef LOGIN_NO_ENDOPT
1597 "-p", "-f", pw->pw_name, (char *)NULL);
1599 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1602 /* Login couldn't be executed, die. */
1609 child_close_fds(void)
1611 if (packet_get_connection_in() == packet_get_connection_out())
1612 close(packet_get_connection_in());
1614 close(packet_get_connection_in());
1615 close(packet_get_connection_out());
1618 * Close all descriptors related to channels. They will still remain
1619 * open in the parent.
1621 /* XXX better use close-on-exec? -markus */
1622 channel_close_all();
1625 * Close any extra file descriptors. Note that there may still be
1626 * descriptors left by system functions. They will be closed later.
1631 * Close any extra open file descriptors so that we don't have them
1632 * hanging around in clients. Note that we want to do this after
1633 * initgroups, because at least on Solaris 2.3 it leaves file
1636 closefrom(STDERR_FILENO + 1);
1640 * Performs common processing for the child, such as setting up the
1641 * environment, closing extra file descriptors, setting the user and group
1642 * ids, and executing the command or shell.
1646 do_child(Session *s, const char *command)
1648 extern char **environ;
1650 char *argv[ARGV_MAX];
1651 const char *shell, *shell0, *hostname = NULL;
1652 struct passwd *pw = s->pw;
1655 /* remove hostkey from the child's memory */
1656 destroy_sensitive_data();
1658 /* Force a password change */
1659 if (s->authctxt->force_pwchange) {
1660 do_setusercontext(pw);
1666 /* login(1) is only called if we execute the login shell */
1667 if (options.use_login && command != NULL)
1668 options.use_login = 0;
1671 cray_setup(pw->pw_uid, pw->pw_name, command);
1672 #endif /* _UNICOS */
1675 * Login(1) does this as well, and it needs uid 0 for the "-h"
1676 * switch, so we let login(1) to this for us.
1678 if (!options.use_login) {
1680 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1681 if (!check_quietlogin(s, command))
1683 #else /* HAVE_OSF_SIA */
1684 /* When PAM is enabled we rely on it to do the nologin check */
1685 if (!options.use_pam)
1687 do_setusercontext(pw);
1689 * PAM session modules in do_setusercontext may have
1690 * generated messages, so if this in an interactive
1691 * login then display them too.
1693 if (!check_quietlogin(s, command))
1695 #endif /* HAVE_OSF_SIA */
1699 if (options.use_pam && !options.use_login && !is_pam_session_open()) {
1700 debug3("PAM session not opened, exiting");
1707 * Get the shell from the password data. An empty shell field is
1708 * legal, and means /bin/sh.
1710 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1713 * Make sure $SHELL points to the shell from the password file,
1714 * even if shell is overridden from login.conf
1716 env = do_setup_env(s, shell);
1718 #ifdef HAVE_LOGIN_CAP
1719 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1722 /* we have to stash the hostname before we close our socket. */
1723 if (options.use_login)
1724 hostname = get_remote_name_or_ip(utmp_len,
1727 * Close the connection descriptors; note that this is the child, and
1728 * the server will still have the socket open, and it is important
1729 * that we do not shutdown it. Note that the descriptors cannot be
1730 * closed before building the environment, as we call
1731 * get_remote_ipaddr there.
1736 * Must take new environment into use so that .ssh/rc,
1737 * /etc/ssh/sshrc and xauth are run in the proper environment.
1741 #if defined(KRB5) && defined(USE_AFS)
1743 * At this point, we check to see if AFS is active and if we have
1744 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1745 * if we can (and need to) extend the ticket into an AFS token. If
1746 * we don't do this, we run into potential problems if the user's
1747 * home directory is in AFS and it's not world-readable.
1750 if (options.kerberos_get_afs_token && k_hasafs() &&
1751 (s->authctxt->krb5_ctx != NULL)) {
1754 debug("Getting AFS token");
1758 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1759 krb5_afslog(s->authctxt->krb5_ctx,
1760 s->authctxt->krb5_fwd_ccache, cell, NULL);
1762 krb5_afslog_home(s->authctxt->krb5_ctx,
1763 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1767 /* Change current directory to the user's home directory. */
1768 if (chdir(pw->pw_dir) < 0) {
1769 /* Suppress missing homedir warning for chroot case */
1770 #ifdef HAVE_LOGIN_CAP
1771 r = login_getcapbool(lc, "requirehome", 0);
1773 if (r || options.chroot_directory == NULL ||
1774 strcasecmp(options.chroot_directory, "none") == 0)
1775 fprintf(stderr, "Could not chdir to home "
1776 "directory %s: %s\n", pw->pw_dir,
1782 closefrom(STDERR_FILENO + 1);
1784 if (!options.use_login)
1785 do_rc_files(s, shell);
1787 /* restore SIGPIPE for child */
1788 signal(SIGPIPE, SIG_DFL);
1790 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1791 printf("This service allows sftp connections only.\n");
1794 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1795 extern int optind, optreset;
1799 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1800 args = xstrdup(command ? command : "sftp-server");
1801 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1802 if (i < ARGV_MAX - 1)
1805 optind = optreset = 1;
1806 __progname = argv[0];
1808 ssh_selinux_change_context("sftpd_t");
1810 exit(sftp_server_main(i, argv, s->pw));
1815 if (options.use_login) {
1816 launch_login(pw, hostname);
1820 /* Get the last component of the shell name. */
1821 if ((shell0 = strrchr(shell, '/')) != NULL)
1827 * If we have no command, execute the shell. In this case, the shell
1828 * name to be passed in argv[0] is preceded by '-' to indicate that
1829 * this is a login shell.
1834 /* Start the shell. Set initial character to '-'. */
1837 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1838 >= sizeof(argv0) - 1) {
1844 /* Execute the shell. */
1847 execve(shell, argv, env);
1849 /* Executing the shell failed. */
1854 * Execute the command using the user's shell. This uses the -c
1855 * option to execute the command.
1857 argv[0] = (char *) shell0;
1859 argv[2] = (char *) command;
1861 execve(shell, argv, env);
1867 session_unused(int id)
1869 debug3("%s: session id %d unused", __func__, id);
1870 if (id >= options.max_sessions ||
1871 id >= sessions_nalloc) {
1872 fatal("%s: insane session id %d (max %d nalloc %d)",
1873 __func__, id, options.max_sessions, sessions_nalloc);
1875 bzero(&sessions[id], sizeof(*sessions));
1876 sessions[id].self = id;
1877 sessions[id].used = 0;
1878 sessions[id].chanid = -1;
1879 sessions[id].ptyfd = -1;
1880 sessions[id].ttyfd = -1;
1881 sessions[id].ptymaster = -1;
1882 sessions[id].x11_chanids = NULL;
1883 sessions[id].next_unused = sessions_first_unused;
1884 sessions_first_unused = id;
1892 if (sessions_first_unused == -1) {
1893 if (sessions_nalloc >= options.max_sessions)
1895 debug2("%s: allocate (allocated %d max %d)",
1896 __func__, sessions_nalloc, options.max_sessions);
1897 tmp = xrealloc(sessions, sessions_nalloc + 1,
1900 error("%s: cannot allocate %d sessions",
1901 __func__, sessions_nalloc + 1);
1905 session_unused(sessions_nalloc++);
1908 if (sessions_first_unused >= sessions_nalloc ||
1909 sessions_first_unused < 0) {
1910 fatal("%s: insane first_unused %d max %d nalloc %d",
1911 __func__, sessions_first_unused, options.max_sessions,
1915 s = &sessions[sessions_first_unused];
1917 fatal("%s: session %d already used",
1918 __func__, sessions_first_unused);
1920 sessions_first_unused = s->next_unused;
1922 s->next_unused = -1;
1923 debug("session_new: session %d", s->self);
1932 for (i = 0; i < sessions_nalloc; i++) {
1933 Session *s = &sessions[i];
1935 debug("dump: used %d next_unused %d session %d %p "
1936 "channel %d pid %ld",
1947 session_open(Authctxt *authctxt, int chanid)
1949 Session *s = session_new();
1950 debug("session_open: channel %d", chanid);
1952 error("no more sessions");
1955 s->authctxt = authctxt;
1956 s->pw = authctxt->pw;
1957 if (s->pw == NULL || !authctxt->valid)
1958 fatal("no user for session %d", s->self);
1959 debug("session_open: session %d: link with channel %d", s->self, chanid);
1965 session_by_tty(char *tty)
1968 for (i = 0; i < sessions_nalloc; i++) {
1969 Session *s = &sessions[i];
1970 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1971 debug("session_by_tty: session %d tty %s", i, tty);
1975 debug("session_by_tty: unknown tty %.100s", tty);
1981 session_by_channel(int id)
1984 for (i = 0; i < sessions_nalloc; i++) {
1985 Session *s = &sessions[i];
1986 if (s->used && s->chanid == id) {
1987 debug("session_by_channel: session %d channel %d",
1992 debug("session_by_channel: unknown channel %d", id);
1998 session_by_x11_channel(int id)
2002 for (i = 0; i < sessions_nalloc; i++) {
2003 Session *s = &sessions[i];
2005 if (s->x11_chanids == NULL || !s->used)
2007 for (j = 0; s->x11_chanids[j] != -1; j++) {
2008 if (s->x11_chanids[j] == id) {
2009 debug("session_by_x11_channel: session %d "
2010 "channel %d", s->self, id);
2015 debug("session_by_x11_channel: unknown channel %d", id);
2021 session_by_pid(pid_t pid)
2024 debug("session_by_pid: pid %ld", (long)pid);
2025 for (i = 0; i < sessions_nalloc; i++) {
2026 Session *s = &sessions[i];
2027 if (s->used && s->pid == pid)
2030 error("session_by_pid: unknown pid %ld", (long)pid);
2036 session_window_change_req(Session *s)
2038 s->col = packet_get_int();
2039 s->row = packet_get_int();
2040 s->xpixel = packet_get_int();
2041 s->ypixel = packet_get_int();
2043 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
2048 session_pty_req(Session *s)
2054 debug("Allocating a pty not permitted for this authentication.");
2057 if (s->ttyfd != -1) {
2058 packet_disconnect("Protocol error: you already have a pty.");
2062 s->term = packet_get_string(&len);
2065 s->col = packet_get_int();
2066 s->row = packet_get_int();
2068 s->row = packet_get_int();
2069 s->col = packet_get_int();
2071 s->xpixel = packet_get_int();
2072 s->ypixel = packet_get_int();
2074 if (strcmp(s->term, "") == 0) {
2079 /* Allocate a pty and open it. */
2080 debug("Allocating pty.");
2081 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
2088 error("session_pty_req: session %d alloc failed", s->self);
2091 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
2093 /* for SSH1 the tty modes length is not given */
2095 n_bytes = packet_remaining();
2096 tty_parse_modes(s->ttyfd, &n_bytes);
2099 pty_setowner(s->pw, s->tty);
2101 /* Set window size from the packet. */
2102 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
2105 session_proctitle(s);
2110 session_subsystem_req(Session *s)
2115 char *prog, *cmd, *subsys = packet_get_string(&len);
2119 logit("subsystem request for %.100s by user %s", subsys,
2122 for (i = 0; i < options.num_subsystems; i++) {
2123 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
2124 prog = options.subsystem_command[i];
2125 cmd = options.subsystem_args[i];
2126 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
2127 s->is_subsystem = SUBSYSTEM_INT_SFTP;
2128 debug("subsystem: %s", prog);
2130 if (stat(prog, &st) < 0)
2131 debug("subsystem: cannot stat %s: %s",
2132 prog, strerror(errno));
2133 s->is_subsystem = SUBSYSTEM_EXT;
2134 debug("subsystem: exec() %s", cmd);
2136 success = do_exec(s, cmd) == 0;
2142 logit("subsystem request for %.100s failed, subsystem not found",
2150 session_x11_req(Session *s)
2154 if (s->auth_proto != NULL || s->auth_data != NULL) {
2155 error("session_x11_req: session %d: "
2156 "x11 forwarding already active", s->self);
2159 s->single_connection = packet_get_char();
2160 s->auth_proto = packet_get_string(NULL);
2161 s->auth_data = packet_get_string(NULL);
2162 s->screen = packet_get_int();
2165 success = session_setup_x11fwd(s);
2167 xfree(s->auth_proto);
2168 xfree(s->auth_data);
2169 s->auth_proto = NULL;
2170 s->auth_data = NULL;
2176 session_shell_req(Session *s)
2179 return do_exec(s, NULL) == 0;
2183 session_exec_req(Session *s)
2187 char *command = packet_get_string(&len);
2189 success = do_exec(s, command) == 0;
2195 session_break_req(Session *s)
2198 packet_get_int(); /* ignored */
2201 if (s->ttyfd == -1 || tcsendbreak(s->ttyfd, 0) < 0)
2207 session_env_req(Session *s)
2210 u_int name_len, val_len, i;
2212 name = packet_get_string(&name_len);
2213 val = packet_get_string(&val_len);
2216 /* Don't set too many environment variables */
2217 if (s->num_env > 128) {
2218 debug2("Ignoring env request %s: too many env vars", name);
2222 for (i = 0; i < options.num_accept_env; i++) {
2223 if (match_pattern(name, options.accept_env[i])) {
2224 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2225 s->env = xrealloc(s->env, s->num_env + 1,
2227 s->env[s->num_env].name = name;
2228 s->env[s->num_env].val = val;
2233 debug2("Ignoring env request %s: disallowed name", name);
2242 session_auth_agent_req(Session *s)
2244 static int called = 0;
2246 if (no_agent_forwarding_flag || !options.allow_agent_forwarding) {
2247 debug("session_auth_agent_req: no_agent_forwarding_flag");
2254 return auth_input_request_forwarding(s->pw);
2259 session_input_channel_req(Channel *c, const char *rtype)
2264 if ((s = session_by_channel(c->self)) == NULL) {
2265 logit("session_input_channel_req: no session %d req %.100s",
2269 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2272 * a session is in LARVAL state until a shell, a command
2273 * or a subsystem is executed
2275 if (c->type == SSH_CHANNEL_LARVAL) {
2276 if (strcmp(rtype, "shell") == 0) {
2277 success = session_shell_req(s);
2278 } else if (strcmp(rtype, "exec") == 0) {
2279 success = session_exec_req(s);
2280 } else if (strcmp(rtype, "pty-req") == 0) {
2281 success = session_pty_req(s);
2282 } else if (strcmp(rtype, "x11-req") == 0) {
2283 success = session_x11_req(s);
2284 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2285 success = session_auth_agent_req(s);
2286 } else if (strcmp(rtype, "subsystem") == 0) {
2287 success = session_subsystem_req(s);
2288 } else if (strcmp(rtype, "env") == 0) {
2289 success = session_env_req(s);
2292 if (strcmp(rtype, "window-change") == 0) {
2293 success = session_window_change_req(s);
2294 } else if (strcmp(rtype, "break") == 0) {
2295 success = session_break_req(s);
2302 session_set_fds(Session *s, int fdin, int fdout, int fderr, int ignore_fderr,
2306 fatal("session_set_fds: called for proto != 2.0");
2308 * now that have a child and a pipe to the child,
2309 * we can activate our channel and register the fd's
2311 if (s->chanid == -1)
2312 fatal("no channel for session %d", s->self);
2313 if (options.hpn_disabled)
2314 channel_set_fds(s->chanid,
2316 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2317 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2319 channel_set_fds(s->chanid,
2321 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2322 1, is_tty, options.hpn_buffer_size);
2326 * Function to perform pty cleanup. Also called if we get aborted abnormally
2327 * (e.g., due to a dropped connection).
2330 session_pty_cleanup2(Session *s)
2333 error("session_pty_cleanup: no session");
2339 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2341 /* Record that the user has logged out. */
2343 record_logout(s->pid, s->tty, s->pw->pw_name);
2345 /* Release the pseudo-tty. */
2347 pty_release(s->tty);
2350 * Close the server side of the socket pairs. We must do this after
2351 * the pty cleanup, so that another process doesn't get this pty
2352 * while we're still cleaning up.
2354 if (s->ptymaster != -1 && close(s->ptymaster) < 0)
2355 error("close(s->ptymaster/%d): %s",
2356 s->ptymaster, strerror(errno));
2358 /* unlink pty from session */
2363 session_pty_cleanup(Session *s)
2365 PRIVSEP(session_pty_cleanup2(s));
2371 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2386 return "SIG@openssh.com";
2390 session_close_x11(int id)
2394 if ((c = channel_by_id(id)) == NULL) {
2395 debug("session_close_x11: x11 channel %d missing", id);
2397 /* Detach X11 listener */
2398 debug("session_close_x11: detach x11 channel %d", id);
2399 channel_cancel_cleanup(id);
2400 if (c->ostate != CHAN_OUTPUT_CLOSED)
2406 session_close_single_x11(int id, void *arg)
2411 debug3("session_close_single_x11: channel %d", id);
2412 channel_cancel_cleanup(id);
2413 if ((s = session_by_x11_channel(id)) == NULL)
2414 fatal("session_close_single_x11: no x11 channel %d", id);
2415 for (i = 0; s->x11_chanids[i] != -1; i++) {
2416 debug("session_close_single_x11: session %d: "
2417 "closing channel %d", s->self, s->x11_chanids[i]);
2419 * The channel "id" is already closing, but make sure we
2420 * close all of its siblings.
2422 if (s->x11_chanids[i] != id)
2423 session_close_x11(s->x11_chanids[i]);
2425 xfree(s->x11_chanids);
2426 s->x11_chanids = NULL;
2431 if (s->auth_proto) {
2432 xfree(s->auth_proto);
2433 s->auth_proto = NULL;
2436 xfree(s->auth_data);
2437 s->auth_data = NULL;
2439 if (s->auth_display) {
2440 xfree(s->auth_display);
2441 s->auth_display = NULL;
2446 session_exit_message(Session *s, int status)
2450 if ((c = channel_lookup(s->chanid)) == NULL)
2451 fatal("session_exit_message: session %d: no channel %d",
2452 s->self, s->chanid);
2453 debug("session_exit_message: session %d channel %d pid %ld",
2454 s->self, s->chanid, (long)s->pid);
2456 if (WIFEXITED(status)) {
2457 channel_request_start(s->chanid, "exit-status", 0);
2458 packet_put_int(WEXITSTATUS(status));
2460 } else if (WIFSIGNALED(status)) {
2461 channel_request_start(s->chanid, "exit-signal", 0);
2462 packet_put_cstring(sig2name(WTERMSIG(status)));
2464 packet_put_char(WCOREDUMP(status)? 1 : 0);
2465 #else /* WCOREDUMP */
2467 #endif /* WCOREDUMP */
2468 packet_put_cstring("");
2469 packet_put_cstring("");
2472 /* Some weird exit cause. Just exit. */
2473 packet_disconnect("wait returned status %04x.", status);
2476 /* disconnect channel */
2477 debug("session_exit_message: release channel %d", s->chanid);
2480 * Adjust cleanup callback attachment to send close messages when
2481 * the channel gets EOF. The session will be then be closed
2482 * by session_close_by_channel when the childs close their fds.
2484 channel_register_cleanup(c->self, session_close_by_channel, 1);
2487 * emulate a write failure with 'chan_write_failed', nobody will be
2488 * interested in data we write.
2489 * Note that we must not call 'chan_read_failed', since there could
2490 * be some more data waiting in the pipe.
2492 if (c->ostate != CHAN_OUTPUT_CLOSED)
2493 chan_write_failed(c);
2497 session_close(Session *s)
2501 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2503 session_pty_cleanup(s);
2509 xfree(s->x11_chanids);
2510 if (s->auth_display)
2511 xfree(s->auth_display);
2513 xfree(s->auth_data);
2515 xfree(s->auth_proto);
2516 if (s->env != NULL) {
2517 for (i = 0; i < s->num_env; i++) {
2518 xfree(s->env[i].name);
2519 xfree(s->env[i].val);
2523 session_proctitle(s);
2524 session_unused(s->self);
2528 session_close_by_pid(pid_t pid, int status)
2530 Session *s = session_by_pid(pid);
2532 debug("session_close_by_pid: no session for pid %ld",
2536 if (s->chanid != -1)
2537 session_exit_message(s, status);
2539 session_pty_cleanup(s);
2544 * this is called when a channel dies before
2545 * the session 'child' itself dies
2548 session_close_by_channel(int id, void *arg)
2550 Session *s = session_by_channel(id);
2554 debug("session_close_by_channel: no session for id %d", id);
2557 debug("session_close_by_channel: channel %d child %ld",
2560 debug("session_close_by_channel: channel %d: has child", id);
2562 * delay detach of session, but release pty, since
2563 * the fd's to the child are already closed
2566 session_pty_cleanup(s);
2569 /* detach by removing callback */
2570 channel_cancel_cleanup(s->chanid);
2572 /* Close any X11 listeners associated with this session */
2573 if (s->x11_chanids != NULL) {
2574 for (i = 0; s->x11_chanids[i] != -1; i++) {
2575 session_close_x11(s->x11_chanids[i]);
2576 s->x11_chanids[i] = -1;
2585 session_destroy_all(void (*closefunc)(Session *))
2588 for (i = 0; i < sessions_nalloc; i++) {
2589 Session *s = &sessions[i];
2591 if (closefunc != NULL)
2600 session_tty_list(void)
2602 static char buf[1024];
2607 for (i = 0; i < sessions_nalloc; i++) {
2608 Session *s = &sessions[i];
2609 if (s->used && s->ttyfd != -1) {
2611 if (strncmp(s->tty, "/dev/", 5) != 0) {
2612 cp = strrchr(s->tty, '/');
2613 cp = (cp == NULL) ? s->tty : cp + 1;
2618 strlcat(buf, ",", sizeof buf);
2619 strlcat(buf, cp, sizeof buf);
2623 strlcpy(buf, "notty", sizeof buf);
2628 session_proctitle(Session *s)
2631 error("no user for session %d", s->self);
2633 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2637 session_setup_x11fwd(Session *s)
2640 char display[512], auth_display[512];
2641 char hostname[MAXHOSTNAMELEN];
2644 if (no_x11_forwarding_flag) {
2645 packet_send_debug("X11 forwarding disabled in user configuration file.");
2648 if (!options.x11_forwarding) {
2649 debug("X11 forwarding disabled in server configuration file.");
2652 if (!options.xauth_location ||
2653 (stat(options.xauth_location, &st) == -1)) {
2654 packet_send_debug("No xauth program; cannot forward with spoofing.");
2657 if (options.use_login) {
2658 packet_send_debug("X11 forwarding disabled; "
2659 "not compatible with UseLogin=yes.");
2662 if (s->display != NULL) {
2663 debug("X11 display already set.");
2666 if (x11_create_display_inet(options.x11_display_offset,
2667 options.x11_use_localhost, s->single_connection,
2668 &s->display_number, &s->x11_chanids) == -1) {
2669 debug("x11_create_display_inet failed.");
2672 for (i = 0; s->x11_chanids[i] != -1; i++) {
2673 channel_register_cleanup(s->x11_chanids[i],
2674 session_close_single_x11, 0);
2677 /* Set up a suitable value for the DISPLAY variable. */
2678 if (gethostname(hostname, sizeof(hostname)) < 0)
2679 fatal("gethostname: %.100s", strerror(errno));
2681 * auth_display must be used as the displayname when the
2682 * authorization entry is added with xauth(1). This will be
2683 * different than the DISPLAY string for localhost displays.
2685 if (options.x11_use_localhost) {
2686 snprintf(display, sizeof display, "localhost:%u.%u",
2687 s->display_number, s->screen);
2688 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2689 s->display_number, s->screen);
2690 s->display = xstrdup(display);
2691 s->auth_display = xstrdup(auth_display);
2693 #ifdef IPADDR_IN_DISPLAY
2695 struct in_addr my_addr;
2697 he = gethostbyname(hostname);
2699 error("Can't get IP address for X11 DISPLAY.");
2700 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2703 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2704 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2705 s->display_number, s->screen);
2707 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2708 s->display_number, s->screen);
2710 s->display = xstrdup(display);
2711 s->auth_display = xstrdup(display);
2718 do_authenticated2(Authctxt *authctxt)
2720 server_loop2(authctxt);
2724 do_cleanup(Authctxt *authctxt)
2726 static int called = 0;
2728 debug("do_cleanup");
2730 /* no cleanup if we're in the child for login shell */
2734 /* avoid double cleanup */
2739 if (authctxt == NULL)
2743 if (options.use_pam) {
2745 sshpam_thread_cleanup();
2749 if (!authctxt->authenticated)
2753 if (options.kerberos_ticket_cleanup &&
2755 krb5_cleanup_proc(authctxt);
2759 if (compat20 && options.gss_cleanup_creds)
2760 ssh_gssapi_cleanup_creds();
2763 /* remove agent socket */
2764 auth_sock_cleanup_proc(authctxt->pw);
2767 * Cleanup ptys/utmp only if privsep is disabled,
2768 * or if running in monitor.
2770 if (!use_privsep || mm_is_monitor())
2771 session_destroy_all(session_pty_cleanup2);