1 /* $OpenBSD: session.c,v 1.270 2014/01/31 16:39:19 tedu 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.
39 #include <sys/types.h>
40 #include <sys/param.h>
41 #ifdef HAVE_SYS_STAT_H
42 # include <sys/stat.h>
44 #include <sys/socket.h>
48 #include <arpa/inet.h>
64 #include "openbsd-compat/sys-queue.h"
83 #include "auth-options.h"
85 #include "pathnames.h"
89 #include "serverloop.h"
94 #include "monitor_wrap.h"
97 #if defined(KRB5) && defined(USE_AFS)
102 #include <selinux/selinux.h>
105 #define IS_INTERNAL_SFTP(c) \
106 (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
107 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
108 c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
109 c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
113 Session *session_new(void);
114 void session_set_fds(Session *, int, int, int, int, int);
115 void session_pty_cleanup(Session *);
116 void session_proctitle(Session *);
117 int session_setup_x11fwd(Session *);
118 int do_exec_pty(Session *, const char *);
119 int do_exec_no_pty(Session *, const char *);
120 int do_exec(Session *, const char *);
121 void do_login(Session *, const char *);
122 #ifdef LOGIN_NEEDS_UTMPX
123 static void do_pre_login(Session *s);
125 void do_child(Session *, const char *);
127 int check_quietlogin(Session *, const char *);
129 static void do_authenticated1(Authctxt *);
130 static void do_authenticated2(Authctxt *);
132 static int session_pty_req(Session *);
135 extern ServerOptions options;
136 extern char *__progname;
137 extern int log_stderr;
138 extern int debug_flag;
139 extern u_int utmp_len;
140 extern int startup_pipe;
141 extern void destroy_sensitive_data(void);
142 extern Buffer loginmsg;
144 /* original command from peer. */
145 const char *original_command = NULL;
148 static int sessions_first_unused = -1;
149 static int sessions_nalloc = 0;
150 static Session *sessions = NULL;
152 #define SUBSYSTEM_NONE 0
153 #define SUBSYSTEM_EXT 1
154 #define SUBSYSTEM_INT_SFTP 2
155 #define SUBSYSTEM_INT_SFTP_ERROR 3
157 #ifdef HAVE_LOGIN_CAP
161 static int is_child = 0;
163 /* Name and directory of socket for authentication agent forwarding. */
164 static char *auth_sock_name = NULL;
165 static char *auth_sock_dir = NULL;
167 /* removes the agent forwarding socket */
170 auth_sock_cleanup_proc(struct passwd *pw)
172 if (auth_sock_name != NULL) {
173 temporarily_use_uid(pw);
174 unlink(auth_sock_name);
175 rmdir(auth_sock_dir);
176 auth_sock_name = NULL;
182 auth_input_request_forwarding(struct passwd * pw)
186 struct sockaddr_un sunaddr;
188 if (auth_sock_name != NULL) {
189 error("authentication forwarding requested twice.");
193 /* Temporarily drop privileged uid for mkdir/bind. */
194 temporarily_use_uid(pw);
196 /* Allocate a buffer for the socket name, and format the name. */
197 auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
199 /* Create private directory for socket */
200 if (mkdtemp(auth_sock_dir) == NULL) {
201 packet_send_debug("Agent forwarding disabled: "
202 "mkdtemp() failed: %.100s", strerror(errno));
205 auth_sock_dir = NULL;
209 xasprintf(&auth_sock_name, "%s/agent.%ld",
210 auth_sock_dir, (long) getpid());
212 /* Create the socket. */
213 sock = socket(AF_UNIX, SOCK_STREAM, 0);
215 error("socket: %.100s", strerror(errno));
220 /* Bind it to the name. */
221 memset(&sunaddr, 0, sizeof(sunaddr));
222 sunaddr.sun_family = AF_UNIX;
223 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
225 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
226 error("bind: %.100s", strerror(errno));
231 /* Restore the privileged uid. */
234 /* Start listening on the socket. */
235 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
236 error("listen: %.100s", strerror(errno));
241 * Allocate a channel for the authentication agent socket.
242 * Ignore HPN on that one given no improvement expected.
244 nc = channel_new("auth socket",
245 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
246 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
247 0, "auth socket", 1);
248 nc->path = xstrdup(auth_sock_name);
252 free(auth_sock_name);
253 if (auth_sock_dir != NULL) {
254 rmdir(auth_sock_dir);
259 auth_sock_name = NULL;
260 auth_sock_dir = NULL;
265 display_loginmsg(void)
267 if (buffer_len(&loginmsg) > 0) {
268 buffer_append(&loginmsg, "\0", 1);
269 printf("%s", (char *)buffer_ptr(&loginmsg));
270 buffer_clear(&loginmsg);
275 do_authenticated(Authctxt *authctxt)
277 setproctitle("%s", authctxt->pw->pw_name);
279 /* setup the channel layer */
280 if (no_port_forwarding_flag ||
281 (options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
282 channel_disable_adm_local_opens();
284 channel_permit_all_opens();
289 do_authenticated2(authctxt);
291 do_authenticated1(authctxt);
293 do_cleanup(authctxt);
297 * Prepares for an interactive session. This is called after the user has
298 * been successfully authenticated. During this message exchange, pseudo
299 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
300 * are requested, etc.
303 do_authenticated1(Authctxt *authctxt)
307 int success, type, screen_flag;
308 int enable_compression_after_reply = 0;
309 u_int proto_len, data_len, dlen, compression_level = 0;
313 error("no more sessions");
316 s->authctxt = authctxt;
317 s->pw = authctxt->pw;
320 * We stay in this loop until the client requests to execute a shell
326 /* Get a packet from the client. */
327 type = packet_read();
329 /* Process the packet. */
331 case SSH_CMSG_REQUEST_COMPRESSION:
332 compression_level = packet_get_int();
334 if (compression_level < 1 || compression_level > 9) {
335 packet_send_debug("Received invalid compression level %d.",
339 if (options.compression == COMP_NONE) {
340 debug2("compression disabled");
343 /* Enable compression after we have responded with SUCCESS. */
344 enable_compression_after_reply = 1;
348 case SSH_CMSG_REQUEST_PTY:
349 success = session_pty_req(s);
352 case SSH_CMSG_X11_REQUEST_FORWARDING:
353 s->auth_proto = packet_get_string(&proto_len);
354 s->auth_data = packet_get_string(&data_len);
356 screen_flag = packet_get_protocol_flags() &
357 SSH_PROTOFLAG_SCREEN_NUMBER;
358 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
360 if (packet_remaining() == 4) {
362 debug2("Buggy client: "
363 "X11 screen flag missing");
364 s->screen = packet_get_int();
369 success = session_setup_x11fwd(s);
373 s->auth_proto = NULL;
378 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
379 if (!options.allow_agent_forwarding ||
380 no_agent_forwarding_flag || compat13) {
381 debug("Authentication agent forwarding not permitted for this authentication.");
384 debug("Received authentication agent forwarding request.");
385 success = auth_input_request_forwarding(s->pw);
388 case SSH_CMSG_PORT_FORWARD_REQUEST:
389 if (no_port_forwarding_flag) {
390 debug("Port forwarding not permitted for this authentication.");
393 if (!(options.allow_tcp_forwarding & FORWARD_REMOTE)) {
394 debug("Port forwarding not permitted.");
397 debug("Received TCP/IP port forwarding request.");
398 if (channel_input_port_forward_request(s->pw->pw_uid == 0,
399 options.gateway_ports) < 0) {
400 debug("Port forwarding failed.");
406 case SSH_CMSG_MAX_PACKET_SIZE:
407 if (packet_set_maxsize(packet_get_int()) > 0)
411 case SSH_CMSG_EXEC_SHELL:
412 case SSH_CMSG_EXEC_CMD:
413 if (type == SSH_CMSG_EXEC_CMD) {
414 command = packet_get_string(&dlen);
415 debug("Exec command '%.500s'", command);
416 if (do_exec(s, command) != 0)
418 "command execution failed");
421 if (do_exec(s, NULL) != 0)
423 "shell execution failed");
431 * Any unknown messages in this phase are ignored,
432 * and a failure message is returned.
434 logit("Unknown packet type received after authentication: %d", type);
436 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
440 /* Enable compression now that we have replied if appropriate. */
441 if (enable_compression_after_reply) {
442 enable_compression_after_reply = 0;
443 packet_start_compression(compression_level);
450 * This is called to fork and execute a command when we have no tty. This
451 * will call do_child from the child, and server_loop from the parent after
452 * setting up file descriptors and such.
455 do_exec_no_pty(Session *s, const char *command)
460 int pin[2], pout[2], perr[2];
463 fatal("do_exec_no_pty: no session");
465 /* Allocate pipes for communicating with the program. */
467 error("%s: pipe in: %.100s", __func__, strerror(errno));
470 if (pipe(pout) < 0) {
471 error("%s: pipe out: %.100s", __func__, strerror(errno));
476 if (pipe(perr) < 0) {
477 error("%s: pipe err: %.100s", __func__,
486 int inout[2], err[2];
489 fatal("do_exec_no_pty: no session");
491 /* Uses socket pairs to communicate with the program. */
492 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) {
493 error("%s: socketpair #1: %.100s", __func__, strerror(errno));
496 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) {
497 error("%s: socketpair #2: %.100s", __func__,
505 session_proctitle(s);
507 /* Fork the child. */
508 switch ((pid = fork())) {
510 error("%s: fork: %.100s", __func__, strerror(errno));
528 /* Child. Reinitialize the log since the pid has changed. */
529 log_init(__progname, options.log_level,
530 options.log_facility, log_stderr);
533 * Create a new session and process group since the 4.4BSD
534 * setlogin() affects the entire process group.
537 error("setsid failed: %.100s", strerror(errno));
541 * Redirect stdin. We close the parent side of the socket
542 * pair, and make the child side the standard input.
545 if (dup2(pin[0], 0) < 0)
546 perror("dup2 stdin");
549 /* Redirect stdout. */
551 if (dup2(pout[1], 1) < 0)
552 perror("dup2 stdout");
555 /* Redirect stderr. */
557 if (dup2(perr[1], 2) < 0)
558 perror("dup2 stderr");
562 * Redirect stdin, stdout, and stderr. Stdin and stdout will
563 * use the same socket, as some programs (particularly rdist)
564 * seem to depend on it.
568 if (dup2(inout[0], 0) < 0) /* stdin */
569 perror("dup2 stdin");
570 if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */
571 perror("dup2 stdout");
573 if (dup2(err[0], 2) < 0) /* stderr */
574 perror("dup2 stderr");
580 cray_init_job(s->pw); /* set up cray jid and tmpdir */
583 /* Do processing for the child (exec command etc). */
584 do_child(s, command);
591 signal(WJSIGNAL, cray_job_termination_handler);
594 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
598 /* Set interactive/non-interactive mode. */
599 packet_set_interactive(s->display != NULL,
600 options.ip_qos_interactive, options.ip_qos_bulk);
603 * Clear loginmsg, since it's the child's responsibility to display
604 * it to the user, otherwise multiple sessions may accumulate
605 * multiple copies of the login messages.
607 buffer_clear(&loginmsg);
610 /* We are the parent. Close the child sides of the pipes. */
616 session_set_fds(s, pin[1], pout[0], perr[0],
619 /* Enter the interactive session. */
620 server_loop(pid, pin[1], pout[0], perr[0]);
621 /* server_loop has closed pin[1], pout[0], and perr[0]. */
624 /* We are the parent. Close the child sides of the socket pairs. */
629 * Enter the interactive session. Note: server_loop must be able to
630 * handle the case that fdin and fdout are the same.
633 session_set_fds(s, inout[1], inout[1], err[1],
636 server_loop(pid, inout[1], inout[1], err[1]);
637 /* server_loop has closed inout[1] and err[1]. */
644 * This is called to fork and execute a command when we have a tty. This
645 * will call do_child from the child, and server_loop from the parent after
646 * setting up file descriptors, controlling tty, updating wtmp, utmp,
647 * lastlog, and other such operations.
650 do_exec_pty(Session *s, const char *command)
652 int fdout, ptyfd, ttyfd, ptymaster;
656 fatal("do_exec_pty: no session");
661 * Create another descriptor of the pty master side for use as the
662 * standard input. We could use the original descriptor, but this
663 * simplifies code in server_loop. The descriptor is bidirectional.
664 * Do this before forking (and cleanup in the child) so as to
665 * detect and gracefully fail out-of-fd conditions.
667 if ((fdout = dup(ptyfd)) < 0) {
668 error("%s: dup #1: %s", __func__, strerror(errno));
673 /* we keep a reference to the pty master */
674 if ((ptymaster = dup(ptyfd)) < 0) {
675 error("%s: dup #2: %s", __func__, strerror(errno));
682 /* Fork the child. */
683 switch ((pid = fork())) {
685 error("%s: fork: %.100s", __func__, strerror(errno));
697 /* Child. Reinitialize the log because the pid has changed. */
698 log_init(__progname, options.log_level,
699 options.log_facility, log_stderr);
700 /* Close the master side of the pseudo tty. */
703 /* Make the pseudo tty our controlling tty. */
704 pty_make_controlling_tty(&ttyfd, s->tty);
706 /* Redirect stdin/stdout/stderr from the pseudo tty. */
707 if (dup2(ttyfd, 0) < 0)
708 error("dup2 stdin: %s", strerror(errno));
709 if (dup2(ttyfd, 1) < 0)
710 error("dup2 stdout: %s", strerror(errno));
711 if (dup2(ttyfd, 2) < 0)
712 error("dup2 stderr: %s", strerror(errno));
714 /* Close the extra descriptor for the pseudo tty. */
717 /* record login, etc. similar to login(1) */
719 if (!(options.use_login && command == NULL)) {
721 cray_init_job(s->pw); /* set up cray jid and tmpdir */
723 do_login(s, command);
725 # ifdef LOGIN_NEEDS_UTMPX
731 * Do common processing for the child, such as execing
734 do_child(s, command);
741 signal(WJSIGNAL, cray_job_termination_handler);
744 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
749 /* Parent. Close the slave side of the pseudo tty. */
752 /* Enter interactive session. */
753 s->ptymaster = ptymaster;
754 packet_set_interactive(1,
755 options.ip_qos_interactive, options.ip_qos_bulk);
757 session_set_fds(s, ptyfd, fdout, -1, 1, 1);
759 server_loop(pid, ptyfd, fdout, -1);
760 /* server_loop _has_ closed ptyfd and fdout. */
765 #ifdef LOGIN_NEEDS_UTMPX
767 do_pre_login(Session *s)
770 struct sockaddr_storage from;
771 pid_t pid = getpid();
774 * Get IP address of client. If the connection is not a socket, let
775 * the address be 0.0.0.0.
777 memset(&from, 0, sizeof(from));
778 fromlen = sizeof(from);
779 if (packet_connection_is_on_socket()) {
780 if (getpeername(packet_get_connection_in(),
781 (struct sockaddr *)&from, &fromlen) < 0) {
782 debug("getpeername: %.100s", strerror(errno));
787 record_utmp_only(pid, s->tty, s->pw->pw_name,
788 get_remote_name_or_ip(utmp_len, options.use_dns),
789 (struct sockaddr *)&from, fromlen);
794 * This is called to fork and execute a command. If another command is
795 * to be forced, execute that instead.
798 do_exec(Session *s, const char *command)
801 const char *forced = NULL;
802 char session_type[1024], *tty = NULL;
804 if (options.adm_forced_command) {
805 original_command = command;
806 command = options.adm_forced_command;
808 } else if (forced_command) {
809 original_command = command;
810 command = forced_command;
811 forced = "(key-option)";
813 if (forced != NULL) {
814 if (IS_INTERNAL_SFTP(command)) {
815 s->is_subsystem = s->is_subsystem ?
816 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
817 } else if (s->is_subsystem)
818 s->is_subsystem = SUBSYSTEM_EXT;
819 snprintf(session_type, sizeof(session_type),
820 "forced-command %s '%.900s'", forced, command);
821 } else if (s->is_subsystem) {
822 snprintf(session_type, sizeof(session_type),
823 "subsystem '%.900s'", s->subsys);
824 } else if (command == NULL) {
825 snprintf(session_type, sizeof(session_type), "shell");
827 /* NB. we don't log unforced commands to preserve privacy */
828 snprintf(session_type, sizeof(session_type), "command");
831 if (s->ttyfd != -1) {
833 if (strncmp(tty, "/dev/", 5) == 0)
837 verbose("Starting session: %s%s%s for %s from %.200s port %d",
839 tty == NULL ? "" : " on ",
840 tty == NULL ? "" : tty,
845 #ifdef SSH_AUDIT_EVENTS
847 PRIVSEP(audit_run_command(command));
848 else if (s->ttyfd == -1) {
849 char *shell = s->pw->pw_shell;
851 if (shell[0] == '\0') /* empty shell means /bin/sh */
853 PRIVSEP(audit_run_command(shell));
857 ret = do_exec_pty(s, command);
859 ret = do_exec_no_pty(s, command);
861 original_command = NULL;
864 * Clear loginmsg: it's the child's responsibility to display
865 * it to the user, otherwise multiple sessions may accumulate
866 * multiple copies of the login messages.
868 buffer_clear(&loginmsg);
873 /* administrative, login(1)-like work */
875 do_login(Session *s, const char *command)
878 struct sockaddr_storage from;
879 struct passwd * pw = s->pw;
880 pid_t pid = getpid();
883 * Get IP address of client. If the connection is not a socket, let
884 * the address be 0.0.0.0.
886 memset(&from, 0, sizeof(from));
887 fromlen = sizeof(from);
888 if (packet_connection_is_on_socket()) {
889 if (getpeername(packet_get_connection_in(),
890 (struct sockaddr *)&from, &fromlen) < 0) {
891 debug("getpeername: %.100s", strerror(errno));
896 /* Record that there was a login on that tty from the remote host. */
898 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
899 get_remote_name_or_ip(utmp_len,
901 (struct sockaddr *)&from, fromlen);
905 * If password change is needed, do it now.
906 * This needs to occur before the ~/.hushlogin check.
908 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
911 s->authctxt->force_pwchange = 0;
912 /* XXX - signal [net] parent to enable forwardings */
916 if (check_quietlogin(s, command))
925 * Display the message of the day.
933 if (options.print_motd) {
934 #ifdef HAVE_LOGIN_CAP
935 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
938 f = fopen("/etc/motd", "r");
941 while (fgets(buf, sizeof(buf), f))
950 * Check for quiet login, either .hushlogin or command given.
953 check_quietlogin(Session *s, const char *command)
956 struct passwd *pw = s->pw;
959 /* Return 1 if .hushlogin exists or a command given. */
962 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
963 #ifdef HAVE_LOGIN_CAP
964 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
967 if (stat(buf, &st) >= 0)
974 * Sets the value of the given variable in the environment. If the variable
975 * already exists, its value is overridden.
978 child_set_env(char ***envp, u_int *envsizep, const char *name,
985 if (strchr(name, '=') != NULL) {
986 error("Invalid environment variable \"%.100s\"", name);
991 * If we're passed an uninitialized list, allocate a single null
992 * entry before continuing.
994 if (*envp == NULL && *envsizep == 0) {
995 *envp = xmalloc(sizeof(char *));
1001 * Find the slot where the value should be stored. If the variable
1002 * already exists, we reuse the slot; otherwise we append a new slot
1003 * at the end of the array, expanding if necessary.
1006 namelen = strlen(name);
1007 for (i = 0; env[i]; i++)
1008 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
1011 /* Reuse the slot. */
1014 /* New variable. Expand if necessary. */
1015 envsize = *envsizep;
1016 if (i >= envsize - 1) {
1017 if (envsize >= 1000)
1018 fatal("child_set_env: too many env vars");
1020 env = (*envp) = xrealloc(env, envsize, sizeof(char *));
1021 *envsizep = envsize;
1023 /* Need to set the NULL pointer at end of array beyond the new slot. */
1027 /* Allocate space and format the variable in the appropriate slot. */
1028 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1029 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1033 * Reads environment variables from the given file and adds/overrides them
1034 * into the environment. If the file does not exist, this does nothing.
1035 * Otherwise, it must consist of empty lines, comments (line starts with '#')
1036 * and assignments of the form name=value. No other forms are allowed.
1039 read_environment_file(char ***env, u_int *envsize,
1040 const char *filename)
1047 f = fopen(filename, "r");
1051 while (fgets(buf, sizeof(buf), f)) {
1052 if (++lineno > 1000)
1053 fatal("Too many lines in environment file %s", filename);
1054 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
1056 if (!*cp || *cp == '#' || *cp == '\n')
1059 cp[strcspn(cp, "\n")] = '\0';
1061 value = strchr(cp, '=');
1062 if (value == NULL) {
1063 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
1068 * Replace the equals sign by nul, and advance value to
1073 child_set_env(env, envsize, cp, value);
1078 #ifdef HAVE_ETC_DEFAULT_LOGIN
1080 * Return named variable from specified environment, or NULL if not present.
1083 child_get_env(char **env, const char *name)
1089 for (i=0; env[i] != NULL; i++)
1090 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
1091 return(env[i] + len + 1);
1096 * Read /etc/default/login.
1097 * We pick up the PATH (or SUPATH for root) and UMASK.
1100 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
1102 char **tmpenv = NULL, *var;
1103 u_int i, tmpenvsize = 0;
1107 * We don't want to copy the whole file to the child's environment,
1108 * so we use a temporary environment and copy the variables we're
1111 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
1117 var = child_get_env(tmpenv, "SUPATH");
1119 var = child_get_env(tmpenv, "PATH");
1121 child_set_env(env, envsize, "PATH", var);
1123 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
1124 if (sscanf(var, "%5lo", &mask) == 1)
1125 umask((mode_t)mask);
1127 for (i = 0; tmpenv[i] != NULL; i++)
1131 #endif /* HAVE_ETC_DEFAULT_LOGIN */
1134 copy_environment(char **source, char ***env, u_int *envsize)
1136 char *var_name, *var_val;
1142 for(i = 0; source[i] != NULL; i++) {
1143 var_name = xstrdup(source[i]);
1144 if ((var_val = strstr(var_name, "=")) == NULL) {
1150 debug3("Copy environment: %s=%s", var_name, var_val);
1151 child_set_env(env, envsize, var_name, var_val);
1158 do_setup_env(Session *s, const char *shell)
1163 struct passwd *pw = s->pw;
1164 #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
1167 extern char **environ;
1171 /* Initialize the environment. */
1173 env = xcalloc(envsize, sizeof(char *));
1178 * The Windows environment contains some setting which are
1179 * important for a running system. They must not be dropped.
1184 p = fetch_windows_environment();
1185 copy_environment(p, &env, &envsize);
1186 free_windows_environment(p);
1191 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1194 /* Allow any GSSAPI methods that we've used to alter
1195 * the childs environment as they see fit
1197 ssh_gssapi_do_child(&env, &envsize);
1200 if (!options.use_login) {
1201 /* Set basic environment. */
1202 for (i = 0; i < s->num_env; i++)
1203 child_set_env(&env, &envsize, s->env[i].name,
1206 child_set_env(&env, &envsize, "USER", pw->pw_name);
1207 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1209 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1211 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1212 snprintf(buf, sizeof buf, "%.200s/%.50s",
1213 _PATH_MAILDIR, pw->pw_name);
1214 child_set_env(&env, &envsize, "MAIL", buf);
1215 #ifdef HAVE_LOGIN_CAP
1216 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1217 child_set_env(&env, &envsize, "TERM", "su");
1219 environ = xmalloc(sizeof(char *));
1221 (void) setusercontext(lc, pw, pw->pw_uid,
1222 LOGIN_SETENV|LOGIN_SETPATH);
1223 copy_environment(environ, &env, &envsize);
1224 for (var = environ; *var != NULL; ++var)
1228 #else /* HAVE_LOGIN_CAP */
1229 # ifndef HAVE_CYGWIN
1231 * There's no standard path on Windows. The path contains
1232 * important components pointing to the system directories,
1233 * needed for loading shared libraries. So the path better
1234 * remains intact here.
1236 # ifdef HAVE_ETC_DEFAULT_LOGIN
1237 read_etc_default_login(&env, &envsize, pw->pw_uid);
1238 path = child_get_env(env, "PATH");
1239 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1240 if (path == NULL || *path == '\0') {
1241 child_set_env(&env, &envsize, "PATH",
1242 s->pw->pw_uid == 0 ?
1243 SUPERUSER_PATH : _PATH_STDPATH);
1245 # endif /* HAVE_CYGWIN */
1246 #endif /* HAVE_LOGIN_CAP */
1248 /* Normal systems set SHELL by default. */
1249 child_set_env(&env, &envsize, "SHELL", shell);
1252 /* Set custom environment options from RSA authentication. */
1253 if (!options.use_login) {
1254 while (custom_environment) {
1255 struct envstring *ce = custom_environment;
1258 for (i = 0; str[i] != '=' && str[i]; i++)
1260 if (str[i] == '=') {
1262 child_set_env(&env, &envsize, str, str + i + 1);
1264 custom_environment = ce->next;
1270 /* SSH_CLIENT deprecated */
1271 snprintf(buf, sizeof buf, "%.50s %d %d",
1272 get_remote_ipaddr(), get_remote_port(), get_local_port());
1273 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1275 laddr = get_local_ipaddr(packet_get_connection_in());
1276 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1277 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1279 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1282 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1284 child_set_env(&env, &envsize, "TERM", s->term);
1286 child_set_env(&env, &envsize, "DISPLAY", s->display);
1287 if (original_command)
1288 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1292 if (cray_tmpdir[0] != '\0')
1293 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1294 #endif /* _UNICOS */
1297 * Since we clear KRB5CCNAME at startup, if it's set now then it
1298 * must have been set by a native authentication method (eg AIX or
1299 * SIA), so copy it to the child.
1304 if ((cp = getenv("KRB5CCNAME")) != NULL)
1305 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1312 if ((cp = getenv("AUTHSTATE")) != NULL)
1313 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1314 read_environment_file(&env, &envsize, "/etc/environment");
1318 if (s->authctxt->krb5_ccname)
1319 child_set_env(&env, &envsize, "KRB5CCNAME",
1320 s->authctxt->krb5_ccname);
1324 * Pull in any environment variables that may have
1327 if (options.use_pam) {
1330 p = fetch_pam_child_environment();
1331 copy_environment(p, &env, &envsize);
1332 free_pam_environment(p);
1334 p = fetch_pam_environment();
1335 copy_environment(p, &env, &envsize);
1336 free_pam_environment(p);
1338 #endif /* USE_PAM */
1340 if (auth_sock_name != NULL)
1341 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1344 /* read $HOME/.ssh/environment. */
1345 if (options.permit_user_env && !options.use_login) {
1346 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1347 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1348 read_environment_file(&env, &envsize, buf);
1351 /* dump the environment */
1352 fprintf(stderr, "Environment:\n");
1353 for (i = 0; env[i]; i++)
1354 fprintf(stderr, " %.200s\n", env[i]);
1360 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1361 * first in this order).
1364 do_rc_files(Session *s, const char *shell)
1372 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1374 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1375 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1376 !no_user_rc && stat(_PATH_SSH_USER_RC, &st) >= 0) {
1377 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1378 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1380 fprintf(stderr, "Running %s\n", cmd);
1381 f = popen(cmd, "w");
1384 fprintf(f, "%s %s\n", s->auth_proto,
1388 fprintf(stderr, "Could not run %s\n",
1390 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1392 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1393 _PATH_SSH_SYSTEM_RC);
1394 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1397 fprintf(f, "%s %s\n", s->auth_proto,
1401 fprintf(stderr, "Could not run %s\n",
1402 _PATH_SSH_SYSTEM_RC);
1403 } else if (do_xauth && options.xauth_location != NULL) {
1404 /* Add authority data to .Xauthority if appropriate. */
1407 "Running %.500s remove %.100s\n",
1408 options.xauth_location, s->auth_display);
1410 "%.500s add %.100s %.100s %.100s\n",
1411 options.xauth_location, s->auth_display,
1412 s->auth_proto, s->auth_data);
1414 snprintf(cmd, sizeof cmd, "%s -q -",
1415 options.xauth_location);
1416 f = popen(cmd, "w");
1418 fprintf(f, "remove %s\n",
1420 fprintf(f, "add %s %s %s\n",
1421 s->auth_display, s->auth_proto,
1425 fprintf(stderr, "Could not run %s\n",
1432 do_nologin(struct passwd *pw)
1435 char buf[1024], *nl, *def_nl = _PATH_NOLOGIN;
1438 #ifdef HAVE_LOGIN_CAP
1439 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
1441 nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1443 if (pw->pw_uid == 0)
1447 if (stat(nl, &sb) == -1) {
1453 /* /etc/nologin exists. Print its contents if we can and exit. */
1454 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1455 if ((f = fopen(nl, "r")) != NULL) {
1456 while (fgets(buf, sizeof(buf), f))
1464 * Chroot into a directory after checking it for safety: all path components
1465 * must be root-owned directories with strict permissions.
1468 safely_chroot(const char *path, uid_t uid)
1471 char component[MAXPATHLEN];
1475 fatal("chroot path does not begin at root");
1476 if (strlen(path) >= sizeof(component))
1477 fatal("chroot path too long");
1480 * Descend the path, checking that each component is a
1481 * root-owned directory with strict permissions.
1483 for (cp = path; cp != NULL;) {
1484 if ((cp = strchr(cp, '/')) == NULL)
1485 strlcpy(component, path, sizeof(component));
1488 memcpy(component, path, cp - path);
1489 component[cp - path] = '\0';
1492 debug3("%s: checking '%s'", __func__, component);
1494 if (stat(component, &st) != 0)
1495 fatal("%s: stat(\"%s\"): %s", __func__,
1496 component, strerror(errno));
1497 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1498 fatal("bad ownership or modes for chroot "
1499 "directory %s\"%s\"",
1500 cp == NULL ? "" : "component ", component);
1501 if (!S_ISDIR(st.st_mode))
1502 fatal("chroot path %s\"%s\" is not a directory",
1503 cp == NULL ? "" : "component ", component);
1507 if (chdir(path) == -1)
1508 fatal("Unable to chdir to chroot path \"%s\": "
1509 "%s", path, strerror(errno));
1510 if (chroot(path) == -1)
1511 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1512 if (chdir("/") == -1)
1513 fatal("%s: chdir(/) after chroot: %s",
1514 __func__, strerror(errno));
1515 verbose("Changed root directory to \"%s\"", path);
1518 /* Set login name, uid, gid, and groups. */
1520 do_setusercontext(struct passwd *pw)
1522 char *chroot_path, *tmp;
1524 platform_setusercontext(pw);
1526 if (platform_privileged_uidswap()) {
1527 #ifdef HAVE_LOGIN_CAP
1528 if (setusercontext(lc, pw, pw->pw_uid,
1529 (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1530 perror("unable to set user context");
1534 if (setlogin(pw->pw_name) < 0)
1535 error("setlogin failed: %s", strerror(errno));
1536 if (setgid(pw->pw_gid) < 0) {
1540 /* Initialize the group list. */
1541 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1542 perror("initgroups");
1548 platform_setusercontext_post_groups(pw);
1550 if (options.chroot_directory != NULL &&
1551 strcasecmp(options.chroot_directory, "none") != 0) {
1552 tmp = tilde_expand_filename(options.chroot_directory,
1554 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1555 "u", pw->pw_name, (char *)NULL);
1556 safely_chroot(chroot_path, pw->pw_uid);
1559 /* Make sure we don't attempt to chroot again */
1560 free(options.chroot_directory);
1561 options.chroot_directory = NULL;
1564 #ifdef HAVE_LOGIN_CAP
1565 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1566 perror("unable to set user context (setuser)");
1570 * FreeBSD's setusercontext() will not apply the user's
1571 * own umask setting unless running with the user's UID.
1573 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK);
1576 if (set_id(pw->pw_name) != 0) {
1577 fatal("set_id(%s) Failed", pw->pw_name);
1579 # endif /* USE_LIBIAF */
1580 /* Permanently switch to the desired uid. */
1581 permanently_set_uid(pw);
1583 } else if (options.chroot_directory != NULL &&
1584 strcasecmp(options.chroot_directory, "none") != 0) {
1585 fatal("server lacks privileges to chroot to ChrootDirectory");
1588 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1589 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1593 do_pwchange(Session *s)
1596 fprintf(stderr, "WARNING: Your password has expired.\n");
1597 if (s->ttyfd != -1) {
1599 "You must change your password now and login again!\n");
1603 #ifdef PASSWD_NEEDS_USERNAME
1604 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1607 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1612 "Password change required but no TTY available.\n");
1618 launch_login(struct passwd *pw, const char *hostname)
1620 /* Launch login(1). */
1622 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1623 #ifdef xxxLOGIN_NEEDS_TERM
1624 (s->term ? s->term : "unknown"),
1625 #endif /* LOGIN_NEEDS_TERM */
1626 #ifdef LOGIN_NO_ENDOPT
1627 "-p", "-f", pw->pw_name, (char *)NULL);
1629 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1632 /* Login couldn't be executed, die. */
1639 child_close_fds(void)
1641 extern AuthenticationConnection *auth_conn;
1644 ssh_close_authentication_connection(auth_conn);
1648 if (packet_get_connection_in() == packet_get_connection_out())
1649 close(packet_get_connection_in());
1651 close(packet_get_connection_in());
1652 close(packet_get_connection_out());
1655 * Close all descriptors related to channels. They will still remain
1656 * open in the parent.
1658 /* XXX better use close-on-exec? -markus */
1659 channel_close_all();
1662 * Close any extra file descriptors. Note that there may still be
1663 * descriptors left by system functions. They will be closed later.
1668 * Close any extra open file descriptors so that we don't have them
1669 * hanging around in clients. Note that we want to do this after
1670 * initgroups, because at least on Solaris 2.3 it leaves file
1673 closefrom(STDERR_FILENO + 1);
1677 * Performs common processing for the child, such as setting up the
1678 * environment, closing extra file descriptors, setting the user and group
1679 * ids, and executing the command or shell.
1683 do_child(Session *s, const char *command)
1685 extern char **environ;
1687 char *argv[ARGV_MAX];
1688 const char *shell, *shell0, *hostname = NULL;
1689 struct passwd *pw = s->pw;
1692 /* remove hostkey from the child's memory */
1693 destroy_sensitive_data();
1695 /* Force a password change */
1696 if (s->authctxt->force_pwchange) {
1697 do_setusercontext(pw);
1703 /* login(1) is only called if we execute the login shell */
1704 if (options.use_login && command != NULL)
1705 options.use_login = 0;
1708 cray_setup(pw->pw_uid, pw->pw_name, command);
1709 #endif /* _UNICOS */
1712 * Login(1) does this as well, and it needs uid 0 for the "-h"
1713 * switch, so we let login(1) to this for us.
1715 if (!options.use_login) {
1717 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1718 if (!check_quietlogin(s, command))
1720 #else /* HAVE_OSF_SIA */
1721 /* When PAM is enabled we rely on it to do the nologin check */
1722 if (!options.use_pam)
1724 do_setusercontext(pw);
1726 * PAM session modules in do_setusercontext may have
1727 * generated messages, so if this in an interactive
1728 * login then display them too.
1730 if (!check_quietlogin(s, command))
1732 #endif /* HAVE_OSF_SIA */
1736 if (options.use_pam && !options.use_login && !is_pam_session_open()) {
1737 debug3("PAM session not opened, exiting");
1744 * Get the shell from the password data. An empty shell field is
1745 * legal, and means /bin/sh.
1747 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1750 * Make sure $SHELL points to the shell from the password file,
1751 * even if shell is overridden from login.conf
1753 env = do_setup_env(s, shell);
1755 #ifdef HAVE_LOGIN_CAP
1756 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1759 /* we have to stash the hostname before we close our socket. */
1760 if (options.use_login)
1761 hostname = get_remote_name_or_ip(utmp_len,
1764 * Close the connection descriptors; note that this is the child, and
1765 * the server will still have the socket open, and it is important
1766 * that we do not shutdown it. Note that the descriptors cannot be
1767 * closed before building the environment, as we call
1768 * get_remote_ipaddr there.
1773 * Must take new environment into use so that .ssh/rc,
1774 * /etc/ssh/sshrc and xauth are run in the proper environment.
1778 #if defined(KRB5) && defined(USE_AFS)
1780 * At this point, we check to see if AFS is active and if we have
1781 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1782 * if we can (and need to) extend the ticket into an AFS token. If
1783 * we don't do this, we run into potential problems if the user's
1784 * home directory is in AFS and it's not world-readable.
1787 if (options.kerberos_get_afs_token && k_hasafs() &&
1788 (s->authctxt->krb5_ctx != NULL)) {
1791 debug("Getting AFS token");
1795 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1796 krb5_afslog(s->authctxt->krb5_ctx,
1797 s->authctxt->krb5_fwd_ccache, cell, NULL);
1799 krb5_afslog_home(s->authctxt->krb5_ctx,
1800 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1804 /* Change current directory to the user's home directory. */
1805 if (chdir(pw->pw_dir) < 0) {
1806 /* Suppress missing homedir warning for chroot case */
1807 #ifdef HAVE_LOGIN_CAP
1808 r = login_getcapbool(lc, "requirehome", 0);
1810 if (r || options.chroot_directory == NULL ||
1811 strcasecmp(options.chroot_directory, "none") == 0)
1812 fprintf(stderr, "Could not chdir to home "
1813 "directory %s: %s\n", pw->pw_dir,
1819 closefrom(STDERR_FILENO + 1);
1821 if (!options.use_login)
1822 do_rc_files(s, shell);
1824 /* restore SIGPIPE for child */
1825 signal(SIGPIPE, SIG_DFL);
1827 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1828 printf("This service allows sftp connections only.\n");
1831 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1832 extern int optind, optreset;
1836 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1837 args = xstrdup(command ? command : "sftp-server");
1838 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1839 if (i < ARGV_MAX - 1)
1842 optind = optreset = 1;
1843 __progname = argv[0];
1845 ssh_selinux_change_context("sftpd_t");
1847 exit(sftp_server_main(i, argv, s->pw));
1852 if (options.use_login) {
1853 launch_login(pw, hostname);
1857 /* Get the last component of the shell name. */
1858 if ((shell0 = strrchr(shell, '/')) != NULL)
1864 * If we have no command, execute the shell. In this case, the shell
1865 * name to be passed in argv[0] is preceded by '-' to indicate that
1866 * this is a login shell.
1871 /* Start the shell. Set initial character to '-'. */
1874 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1875 >= sizeof(argv0) - 1) {
1881 /* Execute the shell. */
1884 execve(shell, argv, env);
1886 /* Executing the shell failed. */
1891 * Execute the command using the user's shell. This uses the -c
1892 * option to execute the command.
1894 argv[0] = (char *) shell0;
1896 argv[2] = (char *) command;
1898 execve(shell, argv, env);
1904 session_unused(int id)
1906 debug3("%s: session id %d unused", __func__, id);
1907 if (id >= options.max_sessions ||
1908 id >= sessions_nalloc) {
1909 fatal("%s: insane session id %d (max %d nalloc %d)",
1910 __func__, id, options.max_sessions, sessions_nalloc);
1912 memset(&sessions[id], 0, sizeof(*sessions));
1913 sessions[id].self = id;
1914 sessions[id].used = 0;
1915 sessions[id].chanid = -1;
1916 sessions[id].ptyfd = -1;
1917 sessions[id].ttyfd = -1;
1918 sessions[id].ptymaster = -1;
1919 sessions[id].x11_chanids = NULL;
1920 sessions[id].next_unused = sessions_first_unused;
1921 sessions_first_unused = id;
1929 if (sessions_first_unused == -1) {
1930 if (sessions_nalloc >= options.max_sessions)
1932 debug2("%s: allocate (allocated %d max %d)",
1933 __func__, sessions_nalloc, options.max_sessions);
1934 tmp = xrealloc(sessions, sessions_nalloc + 1,
1937 error("%s: cannot allocate %d sessions",
1938 __func__, sessions_nalloc + 1);
1942 session_unused(sessions_nalloc++);
1945 if (sessions_first_unused >= sessions_nalloc ||
1946 sessions_first_unused < 0) {
1947 fatal("%s: insane first_unused %d max %d nalloc %d",
1948 __func__, sessions_first_unused, options.max_sessions,
1952 s = &sessions[sessions_first_unused];
1954 fatal("%s: session %d already used",
1955 __func__, sessions_first_unused);
1957 sessions_first_unused = s->next_unused;
1959 s->next_unused = -1;
1960 debug("session_new: session %d", s->self);
1969 for (i = 0; i < sessions_nalloc; i++) {
1970 Session *s = &sessions[i];
1972 debug("dump: used %d next_unused %d session %d %p "
1973 "channel %d pid %ld",
1984 session_open(Authctxt *authctxt, int chanid)
1986 Session *s = session_new();
1987 debug("session_open: channel %d", chanid);
1989 error("no more sessions");
1992 s->authctxt = authctxt;
1993 s->pw = authctxt->pw;
1994 if (s->pw == NULL || !authctxt->valid)
1995 fatal("no user for session %d", s->self);
1996 debug("session_open: session %d: link with channel %d", s->self, chanid);
2002 session_by_tty(char *tty)
2005 for (i = 0; i < sessions_nalloc; i++) {
2006 Session *s = &sessions[i];
2007 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
2008 debug("session_by_tty: session %d tty %s", i, tty);
2012 debug("session_by_tty: unknown tty %.100s", tty);
2018 session_by_channel(int id)
2021 for (i = 0; i < sessions_nalloc; i++) {
2022 Session *s = &sessions[i];
2023 if (s->used && s->chanid == id) {
2024 debug("session_by_channel: session %d channel %d",
2029 debug("session_by_channel: unknown channel %d", id);
2035 session_by_x11_channel(int id)
2039 for (i = 0; i < sessions_nalloc; i++) {
2040 Session *s = &sessions[i];
2042 if (s->x11_chanids == NULL || !s->used)
2044 for (j = 0; s->x11_chanids[j] != -1; j++) {
2045 if (s->x11_chanids[j] == id) {
2046 debug("session_by_x11_channel: session %d "
2047 "channel %d", s->self, id);
2052 debug("session_by_x11_channel: unknown channel %d", id);
2058 session_by_pid(pid_t pid)
2061 debug("session_by_pid: pid %ld", (long)pid);
2062 for (i = 0; i < sessions_nalloc; i++) {
2063 Session *s = &sessions[i];
2064 if (s->used && s->pid == pid)
2067 error("session_by_pid: unknown pid %ld", (long)pid);
2073 session_window_change_req(Session *s)
2075 s->col = packet_get_int();
2076 s->row = packet_get_int();
2077 s->xpixel = packet_get_int();
2078 s->ypixel = packet_get_int();
2080 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
2085 session_pty_req(Session *s)
2090 if (no_pty_flag || !options.permit_tty) {
2091 debug("Allocating a pty not permitted for this authentication.");
2094 if (s->ttyfd != -1) {
2095 packet_disconnect("Protocol error: you already have a pty.");
2099 s->term = packet_get_string(&len);
2102 s->col = packet_get_int();
2103 s->row = packet_get_int();
2105 s->row = packet_get_int();
2106 s->col = packet_get_int();
2108 s->xpixel = packet_get_int();
2109 s->ypixel = packet_get_int();
2111 if (strcmp(s->term, "") == 0) {
2116 /* Allocate a pty and open it. */
2117 debug("Allocating pty.");
2118 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
2124 error("session_pty_req: session %d alloc failed", s->self);
2127 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
2129 /* for SSH1 the tty modes length is not given */
2131 n_bytes = packet_remaining();
2132 tty_parse_modes(s->ttyfd, &n_bytes);
2135 pty_setowner(s->pw, s->tty);
2137 /* Set window size from the packet. */
2138 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
2141 session_proctitle(s);
2146 session_subsystem_req(Session *s)
2154 s->subsys = packet_get_string(&len);
2156 debug2("subsystem request for %.100s by user %s", s->subsys,
2159 for (i = 0; i < options.num_subsystems; i++) {
2160 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
2161 prog = options.subsystem_command[i];
2162 cmd = options.subsystem_args[i];
2163 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
2164 s->is_subsystem = SUBSYSTEM_INT_SFTP;
2165 debug("subsystem: %s", prog);
2167 if (stat(prog, &st) < 0)
2168 debug("subsystem: cannot stat %s: %s",
2169 prog, strerror(errno));
2170 s->is_subsystem = SUBSYSTEM_EXT;
2171 debug("subsystem: exec() %s", cmd);
2173 success = do_exec(s, cmd) == 0;
2179 logit("subsystem request for %.100s by user %s failed, "
2180 "subsystem not found", s->subsys, s->pw->pw_name);
2186 session_x11_req(Session *s)
2190 if (s->auth_proto != NULL || s->auth_data != NULL) {
2191 error("session_x11_req: session %d: "
2192 "x11 forwarding already active", s->self);
2195 s->single_connection = packet_get_char();
2196 s->auth_proto = packet_get_string(NULL);
2197 s->auth_data = packet_get_string(NULL);
2198 s->screen = packet_get_int();
2201 success = session_setup_x11fwd(s);
2203 free(s->auth_proto);
2205 s->auth_proto = NULL;
2206 s->auth_data = NULL;
2212 session_shell_req(Session *s)
2215 return do_exec(s, NULL) == 0;
2219 session_exec_req(Session *s)
2223 char *command = packet_get_string(&len);
2225 success = do_exec(s, command) == 0;
2231 session_break_req(Session *s)
2234 packet_get_int(); /* ignored */
2237 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) < 0)
2243 session_env_req(Session *s)
2246 u_int name_len, val_len, i;
2248 name = packet_get_cstring(&name_len);
2249 val = packet_get_cstring(&val_len);
2252 /* Don't set too many environment variables */
2253 if (s->num_env > 128) {
2254 debug2("Ignoring env request %s: too many env vars", name);
2258 for (i = 0; i < options.num_accept_env; i++) {
2259 if (match_pattern(name, options.accept_env[i])) {
2260 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2261 s->env = xrealloc(s->env, s->num_env + 1,
2263 s->env[s->num_env].name = name;
2264 s->env[s->num_env].val = val;
2269 debug2("Ignoring env request %s: disallowed name", name);
2278 session_auth_agent_req(Session *s)
2280 static int called = 0;
2282 if (no_agent_forwarding_flag || !options.allow_agent_forwarding) {
2283 debug("session_auth_agent_req: no_agent_forwarding_flag");
2290 return auth_input_request_forwarding(s->pw);
2295 session_input_channel_req(Channel *c, const char *rtype)
2300 if ((s = session_by_channel(c->self)) == NULL) {
2301 logit("session_input_channel_req: no session %d req %.100s",
2305 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2308 * a session is in LARVAL state until a shell, a command
2309 * or a subsystem is executed
2311 if (c->type == SSH_CHANNEL_LARVAL) {
2312 if (strcmp(rtype, "shell") == 0) {
2313 success = session_shell_req(s);
2314 } else if (strcmp(rtype, "exec") == 0) {
2315 success = session_exec_req(s);
2316 } else if (strcmp(rtype, "pty-req") == 0) {
2317 success = session_pty_req(s);
2318 } else if (strcmp(rtype, "x11-req") == 0) {
2319 success = session_x11_req(s);
2320 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2321 success = session_auth_agent_req(s);
2322 } else if (strcmp(rtype, "subsystem") == 0) {
2323 success = session_subsystem_req(s);
2324 } else if (strcmp(rtype, "env") == 0) {
2325 success = session_env_req(s);
2328 if (strcmp(rtype, "window-change") == 0) {
2329 success = session_window_change_req(s);
2330 } else if (strcmp(rtype, "break") == 0) {
2331 success = session_break_req(s);
2338 session_set_fds(Session *s, int fdin, int fdout, int fderr, int ignore_fderr,
2342 fatal("session_set_fds: called for proto != 2.0");
2344 * now that have a child and a pipe to the child,
2345 * we can activate our channel and register the fd's
2347 if (s->chanid == -1)
2348 fatal("no channel for session %d", s->self);
2349 if (options.hpn_disabled)
2350 channel_set_fds(s->chanid, fdout, fdin, fderr,
2351 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2352 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2354 channel_set_fds(s->chanid, fdout, fdin, fderr,
2355 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2356 1, is_tty, options.hpn_buffer_size);
2360 * Function to perform pty cleanup. Also called if we get aborted abnormally
2361 * (e.g., due to a dropped connection).
2364 session_pty_cleanup2(Session *s)
2367 error("session_pty_cleanup: no session");
2373 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2375 /* Record that the user has logged out. */
2377 record_logout(s->pid, s->tty, s->pw->pw_name);
2379 /* Release the pseudo-tty. */
2381 pty_release(s->tty);
2384 * Close the server side of the socket pairs. We must do this after
2385 * the pty cleanup, so that another process doesn't get this pty
2386 * while we're still cleaning up.
2388 if (s->ptymaster != -1 && close(s->ptymaster) < 0)
2389 error("close(s->ptymaster/%d): %s",
2390 s->ptymaster, strerror(errno));
2392 /* unlink pty from session */
2397 session_pty_cleanup(Session *s)
2399 PRIVSEP(session_pty_cleanup2(s));
2405 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2420 return "SIG@openssh.com";
2424 session_close_x11(int id)
2428 if ((c = channel_by_id(id)) == NULL) {
2429 debug("session_close_x11: x11 channel %d missing", id);
2431 /* Detach X11 listener */
2432 debug("session_close_x11: detach x11 channel %d", id);
2433 channel_cancel_cleanup(id);
2434 if (c->ostate != CHAN_OUTPUT_CLOSED)
2440 session_close_single_x11(int id, void *arg)
2445 debug3("session_close_single_x11: channel %d", id);
2446 channel_cancel_cleanup(id);
2447 if ((s = session_by_x11_channel(id)) == NULL)
2448 fatal("session_close_single_x11: no x11 channel %d", id);
2449 for (i = 0; s->x11_chanids[i] != -1; i++) {
2450 debug("session_close_single_x11: session %d: "
2451 "closing channel %d", s->self, s->x11_chanids[i]);
2453 * The channel "id" is already closing, but make sure we
2454 * close all of its siblings.
2456 if (s->x11_chanids[i] != id)
2457 session_close_x11(s->x11_chanids[i]);
2459 free(s->x11_chanids);
2460 s->x11_chanids = NULL;
2463 free(s->auth_proto);
2464 s->auth_proto = NULL;
2466 s->auth_data = NULL;
2467 free(s->auth_display);
2468 s->auth_display = NULL;
2472 session_exit_message(Session *s, int status)
2476 if ((c = channel_lookup(s->chanid)) == NULL)
2477 fatal("session_exit_message: session %d: no channel %d",
2478 s->self, s->chanid);
2479 debug("session_exit_message: session %d channel %d pid %ld",
2480 s->self, s->chanid, (long)s->pid);
2482 if (WIFEXITED(status)) {
2483 channel_request_start(s->chanid, "exit-status", 0);
2484 packet_put_int(WEXITSTATUS(status));
2486 } else if (WIFSIGNALED(status)) {
2487 channel_request_start(s->chanid, "exit-signal", 0);
2488 packet_put_cstring(sig2name(WTERMSIG(status)));
2490 packet_put_char(WCOREDUMP(status)? 1 : 0);
2491 #else /* WCOREDUMP */
2493 #endif /* WCOREDUMP */
2494 packet_put_cstring("");
2495 packet_put_cstring("");
2498 /* Some weird exit cause. Just exit. */
2499 packet_disconnect("wait returned status %04x.", status);
2502 /* disconnect channel */
2503 debug("session_exit_message: release channel %d", s->chanid);
2506 * Adjust cleanup callback attachment to send close messages when
2507 * the channel gets EOF. The session will be then be closed
2508 * by session_close_by_channel when the childs close their fds.
2510 channel_register_cleanup(c->self, session_close_by_channel, 1);
2513 * emulate a write failure with 'chan_write_failed', nobody will be
2514 * interested in data we write.
2515 * Note that we must not call 'chan_read_failed', since there could
2516 * be some more data waiting in the pipe.
2518 if (c->ostate != CHAN_OUTPUT_CLOSED)
2519 chan_write_failed(c);
2523 session_close(Session *s)
2527 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2529 session_pty_cleanup(s);
2532 free(s->x11_chanids);
2533 free(s->auth_display);
2535 free(s->auth_proto);
2537 if (s->env != NULL) {
2538 for (i = 0; i < s->num_env; i++) {
2539 free(s->env[i].name);
2540 free(s->env[i].val);
2544 session_proctitle(s);
2545 session_unused(s->self);
2549 session_close_by_pid(pid_t pid, int status)
2551 Session *s = session_by_pid(pid);
2553 debug("session_close_by_pid: no session for pid %ld",
2557 if (s->chanid != -1)
2558 session_exit_message(s, status);
2560 session_pty_cleanup(s);
2565 * this is called when a channel dies before
2566 * the session 'child' itself dies
2569 session_close_by_channel(int id, void *arg)
2571 Session *s = session_by_channel(id);
2575 debug("session_close_by_channel: no session for id %d", id);
2578 debug("session_close_by_channel: channel %d child %ld",
2581 debug("session_close_by_channel: channel %d: has child", id);
2583 * delay detach of session, but release pty, since
2584 * the fd's to the child are already closed
2587 session_pty_cleanup(s);
2590 /* detach by removing callback */
2591 channel_cancel_cleanup(s->chanid);
2593 /* Close any X11 listeners associated with this session */
2594 if (s->x11_chanids != NULL) {
2595 for (i = 0; s->x11_chanids[i] != -1; i++) {
2596 session_close_x11(s->x11_chanids[i]);
2597 s->x11_chanids[i] = -1;
2606 session_destroy_all(void (*closefunc)(Session *))
2609 for (i = 0; i < sessions_nalloc; i++) {
2610 Session *s = &sessions[i];
2612 if (closefunc != NULL)
2621 session_tty_list(void)
2623 static char buf[1024];
2628 for (i = 0; i < sessions_nalloc; i++) {
2629 Session *s = &sessions[i];
2630 if (s->used && s->ttyfd != -1) {
2632 if (strncmp(s->tty, "/dev/", 5) != 0) {
2633 cp = strrchr(s->tty, '/');
2634 cp = (cp == NULL) ? s->tty : cp + 1;
2639 strlcat(buf, ",", sizeof buf);
2640 strlcat(buf, cp, sizeof buf);
2644 strlcpy(buf, "notty", sizeof buf);
2649 session_proctitle(Session *s)
2652 error("no user for session %d", s->self);
2654 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2658 session_setup_x11fwd(Session *s)
2661 char display[512], auth_display[512];
2662 char hostname[MAXHOSTNAMELEN];
2665 if (no_x11_forwarding_flag) {
2666 packet_send_debug("X11 forwarding disabled in user configuration file.");
2669 if (!options.x11_forwarding) {
2670 debug("X11 forwarding disabled in server configuration file.");
2673 if (!options.xauth_location ||
2674 (stat(options.xauth_location, &st) == -1)) {
2675 packet_send_debug("No xauth program; cannot forward with spoofing.");
2678 if (options.use_login) {
2679 packet_send_debug("X11 forwarding disabled; "
2680 "not compatible with UseLogin=yes.");
2683 if (s->display != NULL) {
2684 debug("X11 display already set.");
2687 if (x11_create_display_inet(options.x11_display_offset,
2688 options.x11_use_localhost, s->single_connection,
2689 &s->display_number, &s->x11_chanids) == -1) {
2690 debug("x11_create_display_inet failed.");
2693 for (i = 0; s->x11_chanids[i] != -1; i++) {
2694 channel_register_cleanup(s->x11_chanids[i],
2695 session_close_single_x11, 0);
2698 /* Set up a suitable value for the DISPLAY variable. */
2699 if (gethostname(hostname, sizeof(hostname)) < 0)
2700 fatal("gethostname: %.100s", strerror(errno));
2702 * auth_display must be used as the displayname when the
2703 * authorization entry is added with xauth(1). This will be
2704 * different than the DISPLAY string for localhost displays.
2706 if (options.x11_use_localhost) {
2707 snprintf(display, sizeof display, "localhost:%u.%u",
2708 s->display_number, s->screen);
2709 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2710 s->display_number, s->screen);
2711 s->display = xstrdup(display);
2712 s->auth_display = xstrdup(auth_display);
2714 #ifdef IPADDR_IN_DISPLAY
2716 struct in_addr my_addr;
2718 he = gethostbyname(hostname);
2720 error("Can't get IP address for X11 DISPLAY.");
2721 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2724 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2725 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2726 s->display_number, s->screen);
2728 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2729 s->display_number, s->screen);
2731 s->display = xstrdup(display);
2732 s->auth_display = xstrdup(display);
2739 do_authenticated2(Authctxt *authctxt)
2741 server_loop2(authctxt);
2745 do_cleanup(Authctxt *authctxt)
2747 static int called = 0;
2749 debug("do_cleanup");
2751 /* no cleanup if we're in the child for login shell */
2755 /* avoid double cleanup */
2760 if (authctxt == NULL)
2764 if (options.use_pam) {
2766 sshpam_thread_cleanup();
2770 if (!authctxt->authenticated)
2774 if (options.kerberos_ticket_cleanup &&
2776 krb5_cleanup_proc(authctxt);
2780 if (compat20 && options.gss_cleanup_creds)
2781 ssh_gssapi_cleanup_creds();
2784 /* remove agent socket */
2785 auth_sock_cleanup_proc(authctxt->pw);
2788 * Cleanup ptys/utmp only if privsep is disabled,
2789 * or if running in monitor.
2791 if (!use_privsep || mm_is_monitor())
2792 session_destroy_all(session_pty_cleanup2);