1 /* $OpenBSD: session.c,v 1.233 2008/03/26 21:28:14 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>
80 #include "auth-options.h"
81 #include "pathnames.h"
85 #include "serverloop.h"
90 #include "monitor_wrap.h"
93 #if defined(KRB5) && defined(USE_AFS)
99 Session *session_new(void);
100 void session_set_fds(Session *, int, int, int);
101 void session_pty_cleanup(Session *);
102 void session_proctitle(Session *);
103 int session_setup_x11fwd(Session *);
104 void do_exec_pty(Session *, const char *);
105 void do_exec_no_pty(Session *, const char *);
106 void do_exec(Session *, const char *);
107 void do_login(Session *, const char *);
108 #ifdef LOGIN_NEEDS_UTMPX
109 static void do_pre_login(Session *s);
111 void do_child(Session *, const char *);
113 int check_quietlogin(Session *, const char *);
115 static void do_authenticated1(Authctxt *);
116 static void do_authenticated2(Authctxt *);
118 static int session_pty_req(Session *);
121 static void execute_session_hook(char* prog, Authctxt *authctxt,
122 int startup, int save);
126 extern ServerOptions options;
127 extern char *__progname;
128 extern int log_stderr;
129 extern int debug_flag;
130 extern u_int utmp_len;
131 extern int startup_pipe;
132 extern void destroy_sensitive_data(void);
133 extern Buffer loginmsg;
135 /* original command from peer. */
136 const char *original_command = NULL;
139 #define MAX_SESSIONS 20
140 Session sessions[MAX_SESSIONS];
142 #define SUBSYSTEM_NONE 0
143 #define SUBSYSTEM_EXT 1
144 #define SUBSYSTEM_INT_SFTP 2
146 #ifdef HAVE_LOGIN_CAP
150 static int is_child = 0;
152 /* Name and directory of socket for authentication agent forwarding. */
153 static char *auth_sock_name = NULL;
154 static char *auth_sock_dir = NULL;
156 /* removes the agent forwarding socket */
159 auth_sock_cleanup_proc(struct passwd *pw)
161 if (auth_sock_name != NULL) {
162 temporarily_use_uid(pw);
163 unlink(auth_sock_name);
164 rmdir(auth_sock_dir);
165 auth_sock_name = NULL;
171 auth_input_request_forwarding(struct passwd * pw)
175 struct sockaddr_un sunaddr;
177 if (auth_sock_name != NULL) {
178 error("authentication forwarding requested twice.");
182 /* Temporarily drop privileged uid for mkdir/bind. */
183 temporarily_use_uid(pw);
185 /* Allocate a buffer for the socket name, and format the name. */
186 auth_sock_name = xmalloc(MAXPATHLEN);
187 auth_sock_dir = xmalloc(MAXPATHLEN);
188 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
190 /* Create private directory for socket */
191 if (mkdtemp(auth_sock_dir) == NULL) {
192 packet_send_debug("Agent forwarding disabled: "
193 "mkdtemp() failed: %.100s", strerror(errno));
195 xfree(auth_sock_name);
196 xfree(auth_sock_dir);
197 auth_sock_name = NULL;
198 auth_sock_dir = NULL;
201 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
202 auth_sock_dir, (long) getpid());
204 /* Create the socket. */
205 sock = socket(AF_UNIX, SOCK_STREAM, 0);
207 packet_disconnect("socket: %.100s", strerror(errno));
209 /* Bind it to the name. */
210 memset(&sunaddr, 0, sizeof(sunaddr));
211 sunaddr.sun_family = AF_UNIX;
212 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
214 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0)
215 packet_disconnect("bind: %.100s", strerror(errno));
217 /* Restore the privileged uid. */
220 /* Start listening on the socket. */
221 if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
222 packet_disconnect("listen: %.100s", strerror(errno));
224 /* Allocate a channel for the authentication agent socket. */
225 /* this shouldn't matter if its hpn or not - cjr */
226 nc = channel_new("auth socket",
227 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
228 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
229 0, "auth socket", 1);
230 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
235 display_loginmsg(void)
237 if (buffer_len(&loginmsg) > 0) {
238 buffer_append(&loginmsg, "\0", 1);
239 printf("%s", (char *)buffer_ptr(&loginmsg));
240 buffer_clear(&loginmsg);
245 do_authenticated(Authctxt *authctxt)
247 setproctitle("%s", authctxt->pw->pw_name);
249 /* setup the channel layer */
250 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
251 channel_permit_all_opens();
254 do_authenticated2(authctxt);
256 do_authenticated1(authctxt);
259 if (options.session_hooks_allow &&
260 options.session_hooks_shutdown_cmd)
262 execute_session_hook(options.session_hooks_shutdown_cmd,
264 /* startup = */ 0, /* save = */ 0);
266 if (authctxt->session_env_file)
268 free(authctxt->session_env_file);
273 do_cleanup(authctxt);
277 * Prepares for an interactive session. This is called after the user has
278 * been successfully authenticated. During this message exchange, pseudo
279 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
280 * are requested, etc.
283 do_authenticated1(Authctxt *authctxt)
287 int success, type, screen_flag;
288 int enable_compression_after_reply = 0;
289 u_int proto_len, data_len, dlen, compression_level = 0;
293 error("no more sessions");
296 s->authctxt = authctxt;
297 s->pw = authctxt->pw;
300 * We stay in this loop until the client requests to execute a shell
306 /* Get a packet from the client. */
307 type = packet_read();
309 /* Process the packet. */
311 case SSH_CMSG_REQUEST_COMPRESSION:
312 compression_level = packet_get_int();
314 if (compression_level < 1 || compression_level > 9) {
315 packet_send_debug("Received invalid compression level %d.",
319 if (options.compression == COMP_NONE) {
320 debug2("compression disabled");
323 /* Enable compression after we have responded with SUCCESS. */
324 enable_compression_after_reply = 1;
328 case SSH_CMSG_REQUEST_PTY:
329 success = session_pty_req(s);
332 case SSH_CMSG_X11_REQUEST_FORWARDING:
333 s->auth_proto = packet_get_string(&proto_len);
334 s->auth_data = packet_get_string(&data_len);
336 screen_flag = packet_get_protocol_flags() &
337 SSH_PROTOFLAG_SCREEN_NUMBER;
338 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
340 if (packet_remaining() == 4) {
342 debug2("Buggy client: "
343 "X11 screen flag missing");
344 s->screen = packet_get_int();
349 success = session_setup_x11fwd(s);
351 xfree(s->auth_proto);
353 s->auth_proto = NULL;
358 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
359 if (no_agent_forwarding_flag || compat13) {
360 debug("Authentication agent forwarding not permitted for this authentication.");
363 debug("Received authentication agent forwarding request.");
364 success = auth_input_request_forwarding(s->pw);
367 case SSH_CMSG_PORT_FORWARD_REQUEST:
368 if (no_port_forwarding_flag) {
369 debug("Port forwarding not permitted for this authentication.");
372 if (!options.allow_tcp_forwarding) {
373 debug("Port forwarding not permitted.");
376 debug("Received TCP/IP port forwarding request.");
377 if (channel_input_port_forward_request(s->pw->pw_uid == 0,
378 options.gateway_ports, options.hpn_disabled,
379 options.hpn_buffer_size) < 0) {
380 debug("Port forwarding failed.");
386 case SSH_CMSG_MAX_PACKET_SIZE:
387 if (packet_set_maxsize(packet_get_int()) > 0)
391 case SSH_CMSG_EXEC_SHELL:
392 case SSH_CMSG_EXEC_CMD:
393 if (type == SSH_CMSG_EXEC_CMD) {
394 command = packet_get_string(&dlen);
395 debug("Exec command '%.500s'", command);
407 * Any unknown messages in this phase are ignored,
408 * and a failure message is returned.
410 logit("Unknown packet type received after authentication: %d", type);
412 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
416 /* Enable compression now that we have replied if appropriate. */
417 if (enable_compression_after_reply) {
418 enable_compression_after_reply = 0;
419 packet_start_compression(compression_level);
425 * This is called to fork and execute a command when we have no tty. This
426 * will call do_child from the child, and server_loop from the parent after
427 * setting up file descriptors and such.
430 do_exec_no_pty(Session *s, const char *command)
435 int pin[2], pout[2], perr[2];
436 /* Allocate pipes for communicating with the program. */
437 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
438 packet_disconnect("Could not create pipes: %.100s",
440 #else /* USE_PIPES */
441 int inout[2], err[2];
442 /* Uses socket pairs to communicate with the program. */
443 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
444 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
445 packet_disconnect("Could not create socket pairs: %.100s",
447 #endif /* USE_PIPES */
449 fatal("do_exec_no_pty: no session");
451 session_proctitle(s);
453 /* Fork the child. */
454 if ((pid = fork()) == 0) {
457 /* Child. Reinitialize the log since the pid has changed. */
458 log_init(__progname, options.log_level, options.log_facility, log_stderr);
461 * Create a new session and process group since the 4.4BSD
462 * setlogin() affects the entire process group.
465 error("setsid failed: %.100s", strerror(errno));
469 * Redirect stdin. We close the parent side of the socket
470 * pair, and make the child side the standard input.
473 if (dup2(pin[0], 0) < 0)
474 perror("dup2 stdin");
477 /* Redirect stdout. */
479 if (dup2(pout[1], 1) < 0)
480 perror("dup2 stdout");
483 /* Redirect stderr. */
485 if (dup2(perr[1], 2) < 0)
486 perror("dup2 stderr");
488 #else /* USE_PIPES */
490 * Redirect stdin, stdout, and stderr. Stdin and stdout will
491 * use the same socket, as some programs (particularly rdist)
492 * seem to depend on it.
496 if (dup2(inout[0], 0) < 0) /* stdin */
497 perror("dup2 stdin");
498 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
499 perror("dup2 stdout");
500 if (dup2(err[0], 2) < 0) /* stderr */
501 perror("dup2 stderr");
502 #endif /* USE_PIPES */
505 cray_init_job(s->pw); /* set up cray jid and tmpdir */
508 /* Do processing for the child (exec command etc). */
509 do_child(s, command);
513 signal(WJSIGNAL, cray_job_termination_handler);
517 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
520 packet_disconnect("fork failed: %.100s", strerror(errno));
522 /* Set interactive/non-interactive mode. */
523 packet_set_interactive(s->display != NULL);
525 /* We are the parent. Close the child sides of the pipes. */
531 if (s->is_subsystem) {
535 session_set_fds(s, pin[1], pout[0], perr[0]);
537 /* Enter the interactive session. */
538 server_loop(pid, pin[1], pout[0], perr[0]);
539 /* server_loop has closed pin[1], pout[0], and perr[0]. */
541 #else /* USE_PIPES */
542 /* We are the parent. Close the child sides of the socket pairs. */
547 * Clear loginmsg, since it's the child's responsibility to display
548 * it to the user, otherwise multiple sessions may accumulate
549 * multiple copies of the login messages.
551 buffer_clear(&loginmsg);
554 * Enter the interactive session. Note: server_loop must be able to
555 * handle the case that fdin and fdout are the same.
558 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
560 server_loop(pid, inout[1], inout[1], err[1]);
561 /* server_loop has closed inout[1] and err[1]. */
563 #endif /* USE_PIPES */
567 * This is called to fork and execute a command when we have a tty. This
568 * will call do_child from the child, and server_loop from the parent after
569 * setting up file descriptors, controlling tty, updating wtmp, utmp,
570 * lastlog, and other such operations.
573 do_exec_pty(Session *s, const char *command)
575 int fdout, ptyfd, ttyfd, ptymaster;
579 fatal("do_exec_pty: no session");
583 /* Fork the child. */
584 if ((pid = fork()) == 0) {
587 /* Child. Reinitialize the log because the pid has changed. */
588 log_init(__progname, options.log_level, options.log_facility, log_stderr);
589 /* Close the master side of the pseudo tty. */
592 /* Make the pseudo tty our controlling tty. */
593 pty_make_controlling_tty(&ttyfd, s->tty);
595 /* Redirect stdin/stdout/stderr from the pseudo tty. */
596 if (dup2(ttyfd, 0) < 0)
597 error("dup2 stdin: %s", strerror(errno));
598 if (dup2(ttyfd, 1) < 0)
599 error("dup2 stdout: %s", strerror(errno));
600 if (dup2(ttyfd, 2) < 0)
601 error("dup2 stderr: %s", strerror(errno));
603 /* Close the extra descriptor for the pseudo tty. */
606 /* record login, etc. similar to login(1) */
608 if (!(options.use_login && command == NULL)) {
610 cray_init_job(s->pw); /* set up cray jid and tmpdir */
612 do_login(s, command);
614 # ifdef LOGIN_NEEDS_UTMPX
620 /* Do common processing for the child, such as execing the command. */
621 do_child(s, command);
625 signal(WJSIGNAL, cray_job_termination_handler);
629 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
632 packet_disconnect("fork failed: %.100s", strerror(errno));
635 /* Parent. Close the slave side of the pseudo tty. */
639 * Create another descriptor of the pty master side for use as the
640 * standard input. We could use the original descriptor, but this
641 * simplifies code in server_loop. The descriptor is bidirectional.
645 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
647 /* we keep a reference to the pty master */
648 ptymaster = dup(ptyfd);
650 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
651 s->ptymaster = ptymaster;
653 /* Enter interactive session. */
654 packet_set_interactive(1);
656 session_set_fds(s, ptyfd, fdout, -1);
658 server_loop(pid, ptyfd, fdout, -1);
659 /* server_loop _has_ closed ptyfd and fdout. */
663 #ifdef LOGIN_NEEDS_UTMPX
665 do_pre_login(Session *s)
668 struct sockaddr_storage from;
669 pid_t pid = getpid();
672 * Get IP address of client. If the connection is not a socket, let
673 * the address be 0.0.0.0.
675 memset(&from, 0, sizeof(from));
676 fromlen = sizeof(from);
677 if (packet_connection_is_on_socket()) {
678 if (getpeername(packet_get_connection_in(),
679 (struct sockaddr *)&from, &fromlen) < 0) {
680 debug("getpeername: %.100s", strerror(errno));
685 record_utmp_only(pid, s->tty, s->pw->pw_name,
686 get_remote_name_or_ip(utmp_len, options.use_dns),
687 (struct sockaddr *)&from, fromlen);
692 * This is called to fork and execute a command. If another command is
693 * to be forced, execute that instead.
696 do_exec(Session *s, const char *command)
698 if (options.adm_forced_command) {
699 original_command = command;
700 command = options.adm_forced_command;
701 if (strcmp(INTERNAL_SFTP_NAME, command) == 0)
702 s->is_subsystem = SUBSYSTEM_INT_SFTP;
703 else if (s->is_subsystem)
704 s->is_subsystem = SUBSYSTEM_EXT;
705 debug("Forced command (config) '%.900s'", command);
706 } else if (forced_command) {
707 original_command = command;
708 command = forced_command;
709 if (strcmp(INTERNAL_SFTP_NAME, command) == 0)
710 s->is_subsystem = SUBSYSTEM_INT_SFTP;
711 else if (s->is_subsystem)
712 s->is_subsystem = SUBSYSTEM_EXT;
713 debug("Forced command (key option) '%.900s'", command);
716 #if defined(SESSION_HOOKS)
717 if (options.session_hooks_allow &&
718 (options.session_hooks_startup_cmd ||
719 options.session_hooks_shutdown_cmd))
727 "/tmp/ssh_env_%d%d%d",
731 } while (stat(env_file, &st)==0);
732 s->authctxt->session_env_file = strdup(env_file);
736 #ifdef SSH_AUDIT_EVENTS
738 PRIVSEP(audit_run_command(command));
739 else if (s->ttyfd == -1) {
740 char *shell = s->pw->pw_shell;
742 if (shell[0] == '\0') /* empty shell means /bin/sh */
744 PRIVSEP(audit_run_command(shell));
748 do_exec_pty(s, command);
750 do_exec_no_pty(s, command);
752 original_command = NULL;
755 * Clear loginmsg: it's the child's responsibility to display
756 * it to the user, otherwise multiple sessions may accumulate
757 * multiple copies of the login messages.
759 buffer_clear(&loginmsg);
762 /* administrative, login(1)-like work */
764 do_login(Session *s, const char *command)
767 struct sockaddr_storage from;
768 struct passwd * pw = s->pw;
769 pid_t pid = getpid();
772 * Get IP address of client. If the connection is not a socket, let
773 * the address be 0.0.0.0.
775 memset(&from, 0, sizeof(from));
776 fromlen = sizeof(from);
777 if (packet_connection_is_on_socket()) {
778 if (getpeername(packet_get_connection_in(),
779 (struct sockaddr *) & from, &fromlen) < 0) {
780 debug("getpeername: %.100s", strerror(errno));
785 /* Record that there was a login on that tty from the remote host. */
787 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
788 get_remote_name_or_ip(utmp_len,
790 (struct sockaddr *)&from, fromlen);
794 * If password change is needed, do it now.
795 * This needs to occur before the ~/.hushlogin check.
797 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
800 s->authctxt->force_pwchange = 0;
801 /* XXX - signal [net] parent to enable forwardings */
805 if (check_quietlogin(s, command))
814 * Display the message of the day.
822 if (options.print_motd) {
823 #ifdef HAVE_LOGIN_CAP
824 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
827 f = fopen("/etc/motd", "r");
830 while (fgets(buf, sizeof(buf), f))
839 * Check for quiet login, either .hushlogin or command given.
842 check_quietlogin(Session *s, const char *command)
845 struct passwd *pw = s->pw;
848 /* Return 1 if .hushlogin exists or a command given. */
851 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
852 #ifdef HAVE_LOGIN_CAP
853 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
856 if (stat(buf, &st) >= 0)
863 * Sets the value of the given variable in the environment. If the variable
864 * already exists, its value is overriden.
867 child_set_env(char ***envp, u_int *envsizep, const char *name,
875 * If we're passed an uninitialized list, allocate a single null
876 * entry before continuing.
878 if (*envp == NULL && *envsizep == 0) {
879 *envp = xmalloc(sizeof(char *));
885 * Find the slot where the value should be stored. If the variable
886 * already exists, we reuse the slot; otherwise we append a new slot
887 * at the end of the array, expanding if necessary.
890 namelen = strlen(name);
891 for (i = 0; env[i]; i++)
892 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
895 /* Reuse the slot. */
898 /* New variable. Expand if necessary. */
900 if (i >= envsize - 1) {
902 fatal("child_set_env: too many env vars");
904 env = (*envp) = xrealloc(env, envsize, sizeof(char *));
907 /* Need to set the NULL pointer at end of array beyond the new slot. */
911 /* Allocate space and format the variable in the appropriate slot. */
912 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
913 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
917 * Reads environment variables from the given file and adds/overrides them
918 * into the environment. If the file does not exist, this does nothing.
919 * Otherwise, it must consist of empty lines, comments (line starts with '#')
920 * and assignments of the form name=value. No other forms are allowed.
923 read_environment_file(char ***env, u_int *envsize,
924 const char *filename)
931 f = fopen(filename, "r");
935 while (fgets(buf, sizeof(buf), f)) {
937 fatal("Too many lines in environment file %s", filename);
938 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
940 if (!*cp || *cp == '#' || *cp == '\n')
943 cp[strcspn(cp, "\n")] = '\0';
945 value = strchr(cp, '=');
947 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
952 * Replace the equals sign by nul, and advance value to
957 child_set_env(env, envsize, cp, value);
963 #define SSH_SESSION_ENV_FILE "SSH_SESSION_ENV_FILE"
965 typedef enum { no_op, execute, clear_env, restore_env,
966 read_env, save_or_rm_env } session_action_t;
968 static session_action_t action_order[2][5] = {
969 { clear_env, read_env, execute, save_or_rm_env, restore_env }, /*shutdown*/
970 { execute, read_env, save_or_rm_env, no_op, no_op } /*startup */
974 void execute_session_hook(char* prog, Authctxt *authctxt,
975 int startup, int save)
977 extern char **environ;
980 char **saved_env, **tmpenv;
981 char *env_file = authctxt->session_env_file;
986 switch (action_order[startup][i])
999 authctxt->pw->pw_shell,
1002 debug("executing session hook: [%s]", buf);
1003 setenv(SSH_SESSION_ENV_FILE, env_file, /* overwrite = */ 1);
1005 /* flusing is recommended in the popen(3) man page, to avoid
1006 intermingling of output */
1009 if ((fp=popen(buf, "w")) == NULL)
1011 perror("Unable to run session hook");
1014 status = pclose(fp);
1015 debug2("session hook executed, status=%d", status);
1016 unsetenv(SSH_SESSION_ENV_FILE);
1021 saved_env = environ;
1022 tmpenv = (char**) malloc(sizeof(char*));
1028 environ = saved_env;
1033 if (status==0 && stat(env_file, &st)==0)
1037 debug("reading environment from %s", env_file);
1038 while (environ[envsize++]) ;
1039 read_environment_file(&environ, &envsize, env_file);
1043 case save_or_rm_env:
1044 if (status==0 && save)
1049 debug2("saving environment to %s", env_file);
1050 if ((fp = fopen(env_file, "w")) == NULL) /* hmm: file perms? */
1052 perror("Unable to save session hook info");
1054 while (environ[envcount])
1056 fprintf(fp, "%s\n", environ[envcount++]);
1061 else if (stat(env_file, &st)==0)
1063 debug2("removing environment file %s", env_file);
1073 #ifdef HAVE_ETC_DEFAULT_LOGIN
1075 * Return named variable from specified environment, or NULL if not present.
1078 child_get_env(char **env, const char *name)
1084 for (i=0; env[i] != NULL; i++)
1085 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
1086 return(env[i] + len + 1);
1091 * Read /etc/default/login.
1092 * We pick up the PATH (or SUPATH for root) and UMASK.
1095 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
1097 char **tmpenv = NULL, *var;
1098 u_int i, tmpenvsize = 0;
1102 * We don't want to copy the whole file to the child's environment,
1103 * so we use a temporary environment and copy the variables we're
1106 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
1112 var = child_get_env(tmpenv, "SUPATH");
1114 var = child_get_env(tmpenv, "PATH");
1116 child_set_env(env, envsize, "PATH", var);
1118 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
1119 if (sscanf(var, "%5lo", &mask) == 1)
1120 umask((mode_t)mask);
1122 for (i = 0; tmpenv[i] != NULL; i++)
1126 #endif /* HAVE_ETC_DEFAULT_LOGIN */
1129 copy_environment(char **source, char ***env, u_int *envsize)
1131 char *var_name, *var_val;
1137 for(i = 0; source[i] != NULL; i++) {
1138 var_name = xstrdup(source[i]);
1139 if ((var_val = strstr(var_name, "=")) == NULL) {
1145 debug3("Copy environment: %s=%s", var_name, var_val);
1146 child_set_env(env, envsize, var_name, var_val);
1153 do_setup_env(Session *s, const char *shell)
1158 struct passwd *pw = s->pw;
1159 #ifndef HAVE_LOGIN_CAP
1163 /* Initialize the environment. */
1165 env = xcalloc(envsize, sizeof(char *));
1170 * The Windows environment contains some setting which are
1171 * important for a running system. They must not be dropped.
1176 p = fetch_windows_environment();
1177 copy_environment(p, &env, &envsize);
1178 free_windows_environment(p);
1183 /* Allow any GSSAPI methods that we've used to alter
1184 * the childs environment as they see fit
1186 ssh_gssapi_do_child(&env, &envsize);
1189 if (!options.use_login) {
1190 /* Set basic environment. */
1191 for (i = 0; i < s->num_env; i++)
1192 child_set_env(&env, &envsize, s->env[i].name,
1195 child_set_env(&env, &envsize, "USER", pw->pw_name);
1196 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1198 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1200 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1201 #ifdef HAVE_LOGIN_CAP
1202 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1203 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1205 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1206 #else /* HAVE_LOGIN_CAP */
1207 # ifndef HAVE_CYGWIN
1209 * There's no standard path on Windows. The path contains
1210 * important components pointing to the system directories,
1211 * needed for loading shared libraries. So the path better
1212 * remains intact here.
1214 # ifdef HAVE_ETC_DEFAULT_LOGIN
1215 read_etc_default_login(&env, &envsize, pw->pw_uid);
1216 path = child_get_env(env, "PATH");
1217 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1218 if (path == NULL || *path == '\0') {
1219 child_set_env(&env, &envsize, "PATH",
1220 s->pw->pw_uid == 0 ?
1221 SUPERUSER_PATH : _PATH_STDPATH);
1223 # endif /* HAVE_CYGWIN */
1224 #endif /* HAVE_LOGIN_CAP */
1226 snprintf(buf, sizeof buf, "%.200s/%.50s",
1227 _PATH_MAILDIR, pw->pw_name);
1228 child_set_env(&env, &envsize, "MAIL", buf);
1230 /* Normal systems set SHELL by default. */
1231 child_set_env(&env, &envsize, "SHELL", shell);
1234 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1236 #ifdef GSI /* GSI shared libs typically installed in non-system locations. */
1240 if ((cp = getenv("LD_LIBRARY_PATH")) != NULL)
1241 child_set_env(&env, &envsize, "LD_LIBRARY_PATH", cp);
1242 if ((cp = getenv("LIBPATH")) != NULL)
1243 child_set_env(&env, &envsize, "LIBPATH", cp);
1244 if ((cp = getenv("SHLIB_PATH")) != NULL)
1245 child_set_env(&env, &envsize, "SHLIB_PATH", cp);
1246 if ((cp = getenv("LD_LIBRARYN32_PATH")) != NULL)
1247 child_set_env(&env, &envsize, "LD_LIBRARYN32_PATH",cp);
1248 if ((cp = getenv("LD_LIBRARY64_PATH")) != NULL)
1249 child_set_env(&env, &envsize, "LD_LIBRARY64_PATH",cp);
1253 /* Set custom environment options from RSA authentication. */
1254 if (!options.use_login) {
1255 while (custom_environment) {
1256 struct envstring *ce = custom_environment;
1259 for (i = 0; str[i] != '=' && str[i]; i++)
1261 if (str[i] == '=') {
1263 child_set_env(&env, &envsize, str, str + i + 1);
1265 custom_environment = ce->next;
1271 /* SSH_CLIENT deprecated */
1272 snprintf(buf, sizeof buf, "%.50s %d %d",
1273 get_remote_ipaddr(), get_remote_port(), get_local_port());
1274 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1276 laddr = get_local_ipaddr(packet_get_connection_in());
1277 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1278 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1280 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1283 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1285 child_set_env(&env, &envsize, "TERM", s->term);
1287 child_set_env(&env, &envsize, "DISPLAY", s->display);
1288 if (original_command)
1289 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1293 if (cray_tmpdir[0] != '\0')
1294 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1295 #endif /* _UNICOS */
1298 * Since we clear KRB5CCNAME at startup, if it's set now then it
1299 * must have been set by a native authentication method (eg AIX or
1300 * SIA), so copy it to the child.
1305 if ((cp = getenv("KRB5CCNAME")) != NULL)
1306 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1313 if ((cp = getenv("AUTHSTATE")) != NULL)
1314 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1315 read_environment_file(&env, &envsize, "/etc/environment");
1319 if (s->authctxt->krb5_ccname)
1320 child_set_env(&env, &envsize, "KRB5CCNAME",
1321 s->authctxt->krb5_ccname);
1325 * Pull in any environment variables that may have
1328 if (options.use_pam) {
1331 p = fetch_pam_child_environment();
1332 copy_environment(p, &env, &envsize);
1333 free_pam_environment(p);
1335 p = fetch_pam_environment();
1336 copy_environment(p, &env, &envsize);
1337 free_pam_environment(p);
1339 #endif /* USE_PAM */
1341 if (auth_sock_name != NULL)
1342 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1345 /* read $HOME/.ssh/environment. */
1346 if (options.permit_user_env && !options.use_login) {
1347 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1348 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1349 read_environment_file(&env, &envsize, buf);
1352 /* dump the environment */
1353 fprintf(stderr, "Environment:\n");
1354 for (i = 0; env[i]; i++)
1355 fprintf(stderr, " %.200s\n", env[i]);
1361 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1362 * first in this order).
1365 do_rc_files(Session *s, const char *shell)
1373 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1375 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1376 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1377 !no_user_rc && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1378 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1379 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1381 fprintf(stderr, "Running %s\n", cmd);
1382 f = popen(cmd, "w");
1385 fprintf(f, "%s %s\n", s->auth_proto,
1389 fprintf(stderr, "Could not run %s\n",
1391 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1393 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1394 _PATH_SSH_SYSTEM_RC);
1395 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1398 fprintf(f, "%s %s\n", s->auth_proto,
1402 fprintf(stderr, "Could not run %s\n",
1403 _PATH_SSH_SYSTEM_RC);
1404 } else if (do_xauth && options.xauth_location != NULL) {
1405 /* Add authority data to .Xauthority if appropriate. */
1408 "Running %.500s remove %.100s\n",
1409 options.xauth_location, s->auth_display);
1411 "%.500s add %.100s %.100s %.100s\n",
1412 options.xauth_location, s->auth_display,
1413 s->auth_proto, s->auth_data);
1415 snprintf(cmd, sizeof cmd, "%s -q -",
1416 options.xauth_location);
1417 f = popen(cmd, "w");
1419 fprintf(f, "remove %s\n",
1421 fprintf(f, "add %s %s %s\n",
1422 s->auth_display, s->auth_proto,
1426 fprintf(stderr, "Could not run %s\n",
1433 do_nologin(struct passwd *pw)
1438 #ifdef HAVE_LOGIN_CAP
1439 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1440 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1441 _PATH_NOLOGIN), "r");
1444 f = fopen(_PATH_NOLOGIN, "r");
1447 /* /etc/nologin exists. Print its contents and exit. */
1448 logit("User %.100s not allowed because %s exists",
1449 pw->pw_name, _PATH_NOLOGIN);
1450 while (fgets(buf, sizeof(buf), f))
1459 * Chroot into a directory after checking it for safety: all path components
1460 * must be root-owned directories with strict permissions.
1463 safely_chroot(const char *path, uid_t uid)
1466 char component[MAXPATHLEN];
1470 fatal("chroot path does not begin at root");
1471 if (strlen(path) >= sizeof(component))
1472 fatal("chroot path too long");
1475 * Descend the path, checking that each component is a
1476 * root-owned directory with strict permissions.
1478 for (cp = path; cp != NULL;) {
1479 if ((cp = strchr(cp, '/')) == NULL)
1480 strlcpy(component, path, sizeof(component));
1483 memcpy(component, path, cp - path);
1484 component[cp - path] = '\0';
1487 debug3("%s: checking '%s'", __func__, component);
1489 if (stat(component, &st) != 0)
1490 fatal("%s: stat(\"%s\"): %s", __func__,
1491 component, strerror(errno));
1492 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1493 fatal("bad ownership or modes for chroot "
1494 "directory %s\"%s\"",
1495 cp == NULL ? "" : "component ", component);
1496 if (!S_ISDIR(st.st_mode))
1497 fatal("chroot path %s\"%s\" is not a directory",
1498 cp == NULL ? "" : "component ", component);
1502 if (chdir(path) == -1)
1503 fatal("Unable to chdir to chroot path \"%s\": "
1504 "%s", path, strerror(errno));
1505 if (chroot(path) == -1)
1506 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1507 if (chdir("/") == -1)
1508 fatal("%s: chdir(/) after chroot: %s",
1509 __func__, strerror(errno));
1510 verbose("Changed root directory to \"%s\"", path);
1513 /* Set login name, uid, gid, and groups. */
1515 do_setusercontext(struct passwd *pw)
1517 char *chroot_path, *tmp;
1520 /* Cache selinux status for later use */
1521 (void)ssh_selinux_enabled();
1525 if (getuid() == 0 || geteuid() == 0)
1526 #endif /* HAVE_CYGWIN */
1529 #ifdef HAVE_SETPCRED
1530 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1531 fatal("Failed to set process credentials");
1532 #endif /* HAVE_SETPCRED */
1533 #ifdef HAVE_LOGIN_CAP
1538 if (options.use_pam) {
1539 do_pam_setcred(use_privsep);
1541 # endif /* USE_PAM */
1542 if (setusercontext(lc, pw, pw->pw_uid,
1543 (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1544 perror("unable to set user context");
1548 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1549 /* Sets login uid for accounting */
1550 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1551 error("setluid: %s", strerror(errno));
1552 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1554 if (setlogin(pw->pw_name) < 0)
1555 error("setlogin failed: %s", strerror(errno));
1556 if (setgid(pw->pw_gid) < 0) {
1560 /* Initialize the group list. */
1561 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1562 perror("initgroups");
1568 * PAM credentials may take the form of supplementary groups.
1569 * These will have been wiped by the above initgroups() call.
1570 * Reestablish them here.
1572 if (options.use_pam) {
1573 do_pam_setcred(use_privsep);
1575 # endif /* USE_PAM */
1576 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1577 irix_setusercontext(pw);
1578 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1583 if (set_id(pw->pw_name) != 0) {
1586 # endif /* USE_LIBIAF */
1589 if (options.chroot_directory != NULL &&
1590 strcasecmp(options.chroot_directory, "none") != 0) {
1591 tmp = tilde_expand_filename(options.chroot_directory,
1593 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1594 "u", pw->pw_name, (char *)NULL);
1595 safely_chroot(chroot_path, pw->pw_uid);
1600 #ifdef HAVE_LOGIN_CAP
1601 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1602 perror("unable to set user context (setuser)");
1606 /* Permanently switch to the desired uid. */
1607 permanently_set_uid(pw);
1614 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1615 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1618 ssh_selinux_setup_exec_context(pw->pw_name);
1623 do_pwchange(Session *s)
1626 fprintf(stderr, "WARNING: Your password has expired.\n");
1627 if (s->ttyfd != -1) {
1629 "You must change your password now and login again!\n");
1630 #ifdef PASSWD_NEEDS_USERNAME
1631 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1634 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1639 "Password change required but no TTY available.\n");
1645 launch_login(struct passwd *pw, const char *hostname)
1647 /* Launch login(1). */
1649 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1650 #ifdef xxxLOGIN_NEEDS_TERM
1651 (s->term ? s->term : "unknown"),
1652 #endif /* LOGIN_NEEDS_TERM */
1653 #ifdef LOGIN_NO_ENDOPT
1654 "-p", "-f", pw->pw_name, (char *)NULL);
1656 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1659 /* Login couldn't be executed, die. */
1666 child_close_fds(void)
1670 if (packet_get_connection_in() == packet_get_connection_out())
1671 close(packet_get_connection_in());
1673 close(packet_get_connection_in());
1674 close(packet_get_connection_out());
1677 * Close all descriptors related to channels. They will still remain
1678 * open in the parent.
1680 /* XXX better use close-on-exec? -markus */
1681 channel_close_all();
1684 * Close any extra file descriptors. Note that there may still be
1685 * descriptors left by system functions. They will be closed later.
1690 * Close any extra open file descriptors so that we don't have them
1691 * hanging around in clients. Note that we want to do this after
1692 * initgroups, because at least on Solaris 2.3 it leaves file
1695 for (i = 3; i < 64; i++)
1700 * Performs common processing for the child, such as setting up the
1701 * environment, closing extra file descriptors, setting the user and group
1702 * ids, and executing the command or shell.
1706 do_child(Session *s, const char *command)
1708 extern char **environ;
1710 char *argv[ARGV_MAX];
1711 const char *shell, *shell0, *hostname = NULL;
1712 struct passwd *pw = s->pw;
1715 /* Default place to look for aklog. */
1717 #define KPROGDIR AKLOG_PATH
1719 #define KPROGDIR "/usr/bin/aklog"
1720 #endif /* AKLOG_PATH */
1724 #endif /* AFS_KRB5 */
1726 /* remove hostkey from the child's memory */
1727 destroy_sensitive_data();
1729 /* Force a password change */
1730 if (s->authctxt->force_pwchange) {
1731 do_setusercontext(pw);
1737 /* login(1) is only called if we execute the login shell */
1738 if (options.use_login && command != NULL)
1739 options.use_login = 0;
1742 cray_setup(pw->pw_uid, pw->pw_name, command);
1743 #endif /* _UNICOS */
1746 * Login(1) does this as well, and it needs uid 0 for the "-h"
1747 * switch, so we let login(1) to this for us.
1749 if (!options.use_login) {
1751 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1752 if (!check_quietlogin(s, command))
1754 #else /* HAVE_OSF_SIA */
1755 /* When PAM is enabled we rely on it to do the nologin check */
1756 if (!options.use_pam)
1758 do_setusercontext(pw);
1760 * PAM session modules in do_setusercontext may have
1761 * generated messages, so if this in an interactive
1762 * login then display them too.
1764 if (!check_quietlogin(s, command))
1766 #endif /* HAVE_OSF_SIA */
1770 if (options.use_pam && !options.use_login && !is_pam_session_open()) {
1771 debug3("PAM session not opened, exiting");
1778 * Get the shell from the password data. An empty shell field is
1779 * legal, and means /bin/sh.
1781 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1784 * Make sure $SHELL points to the shell from the password file,
1785 * even if shell is overridden from login.conf
1787 env = do_setup_env(s, shell);
1789 #ifdef HAVE_LOGIN_CAP
1790 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1793 /* we have to stash the hostname before we close our socket. */
1794 if (options.use_login)
1795 hostname = get_remote_name_or_ip(utmp_len,
1798 * Close the connection descriptors; note that this is the child, and
1799 * the server will still have the socket open, and it is important
1800 * that we do not shutdown it. Note that the descriptors cannot be
1801 * closed before building the environment, as we call
1802 * get_remote_ipaddr there.
1807 * Must take new environment into use so that .ssh/rc,
1808 * /etc/ssh/sshrc and xauth are run in the proper environment.
1812 #if defined(KRB5) && defined(USE_AFS)
1814 * At this point, we check to see if AFS is active and if we have
1815 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1816 * if we can (and need to) extend the ticket into an AFS token. If
1817 * we don't do this, we run into potential problems if the user's
1818 * home directory is in AFS and it's not world-readable.
1821 if (options.kerberos_get_afs_token && k_hasafs() &&
1822 (s->authctxt->krb5_ctx != NULL)) {
1825 debug("Getting AFS token");
1829 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1830 krb5_afslog(s->authctxt->krb5_ctx,
1831 s->authctxt->krb5_fwd_ccache, cell, NULL);
1833 krb5_afslog_home(s->authctxt->krb5_ctx,
1834 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1840 /* User has authenticated, and if a ticket was going to be
1841 * passed we would have it. KRB5CCNAME should already be set.
1842 * Now try to get an AFS token using aklog.
1844 if (k_hasafs()) { /* Do we have AFS? */
1846 aklog_path = xstrdup(KPROGDIR);
1849 * Make sure it exists before we try to run it
1851 if (stat(aklog_path, &st) == 0) {
1852 debug("Running %s to get afs token.",aklog_path);
1855 debug("%s does not exist.",aklog_path);
1860 #endif /* AFS_KRB5 */
1862 #ifdef SESSION_HOOKS
1863 if (options.session_hooks_allow &&
1864 options.session_hooks_startup_cmd)
1866 execute_session_hook(options.session_hooks_startup_cmd,
1869 options.session_hooks_shutdown_cmd != NULL);
1873 /* Change current directory to the user's home directory. */
1874 if (chdir(pw->pw_dir) < 0) {
1875 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1876 pw->pw_dir, strerror(errno));
1877 #ifdef HAVE_LOGIN_CAP
1878 if (login_getcapbool(lc, "requirehome", 0))
1883 closefrom(STDERR_FILENO + 1);
1885 if (!options.use_login)
1886 do_rc_files(s, shell);
1888 /* restore SIGPIPE for child */
1889 signal(SIGPIPE, SIG_DFL);
1891 if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1892 extern int optind, optreset;
1896 setproctitle("%s@internal-sftp-server", s->pw->pw_name);
1897 args = strdup(command ? command : "sftp-server");
1898 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1899 if (i < ARGV_MAX - 1)
1902 optind = optreset = 1;
1903 __progname = argv[0];
1904 exit(sftp_server_main(i, argv, s->pw));
1907 if (options.use_login) {
1908 launch_login(pw, hostname);
1912 /* Get the last component of the shell name. */
1913 if ((shell0 = strrchr(shell, '/')) != NULL)
1919 * If we have no command, execute the shell. In this case, the shell
1920 * name to be passed in argv[0] is preceded by '-' to indicate that
1921 * this is a login shell.
1926 /* Start the shell. Set initial character to '-'. */
1929 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1930 >= sizeof(argv0) - 1) {
1936 /* Execute the shell. */
1939 execve(shell, argv, environ);
1941 /* Executing the shell failed. */
1946 * Execute the command using the user's shell. This uses the -c
1947 * option to execute the command.
1949 argv[0] = (char *) shell0;
1951 argv[2] = (char *) command;
1953 execve(shell, argv, environ);
1962 static int did_init = 0;
1964 debug("session_new: init");
1965 for (i = 0; i < MAX_SESSIONS; i++) {
1966 sessions[i].used = 0;
1970 for (i = 0; i < MAX_SESSIONS; i++) {
1971 Session *s = &sessions[i];
1973 memset(s, 0, sizeof(*s));
1979 s->x11_chanids = NULL;
1980 debug("session_new: session %d", i);
1991 for (i = 0; i < MAX_SESSIONS; i++) {
1992 Session *s = &sessions[i];
1993 debug("dump: used %d session %d %p channel %d pid %ld",
2003 session_open(Authctxt *authctxt, int chanid)
2005 Session *s = session_new();
2006 debug("session_open: channel %d", chanid);
2008 error("no more sessions");
2011 s->authctxt = authctxt;
2012 s->pw = authctxt->pw;
2013 if (s->pw == NULL || !authctxt->valid)
2014 fatal("no user for session %d", s->self);
2015 debug("session_open: session %d: link with channel %d", s->self, chanid);
2021 session_by_tty(char *tty)
2024 for (i = 0; i < MAX_SESSIONS; i++) {
2025 Session *s = &sessions[i];
2026 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
2027 debug("session_by_tty: session %d tty %s", i, tty);
2031 debug("session_by_tty: unknown tty %.100s", tty);
2037 session_by_channel(int id)
2040 for (i = 0; i < MAX_SESSIONS; i++) {
2041 Session *s = &sessions[i];
2042 if (s->used && s->chanid == id) {
2043 debug("session_by_channel: session %d channel %d", i, id);
2047 debug("session_by_channel: unknown channel %d", id);
2053 session_by_x11_channel(int id)
2057 for (i = 0; i < MAX_SESSIONS; i++) {
2058 Session *s = &sessions[i];
2060 if (s->x11_chanids == NULL || !s->used)
2062 for (j = 0; s->x11_chanids[j] != -1; j++) {
2063 if (s->x11_chanids[j] == id) {
2064 debug("session_by_x11_channel: session %d "
2065 "channel %d", s->self, id);
2070 debug("session_by_x11_channel: unknown channel %d", id);
2076 session_by_pid(pid_t pid)
2079 debug("session_by_pid: pid %ld", (long)pid);
2080 for (i = 0; i < MAX_SESSIONS; i++) {
2081 Session *s = &sessions[i];
2082 if (s->used && s->pid == pid)
2085 error("session_by_pid: unknown pid %ld", (long)pid);
2091 session_window_change_req(Session *s)
2093 s->col = packet_get_int();
2094 s->row = packet_get_int();
2095 s->xpixel = packet_get_int();
2096 s->ypixel = packet_get_int();
2098 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
2103 session_pty_req(Session *s)
2109 debug("Allocating a pty not permitted for this authentication.");
2112 if (s->ttyfd != -1) {
2113 packet_disconnect("Protocol error: you already have a pty.");
2117 s->term = packet_get_string(&len);
2120 s->col = packet_get_int();
2121 s->row = packet_get_int();
2123 s->row = packet_get_int();
2124 s->col = packet_get_int();
2126 s->xpixel = packet_get_int();
2127 s->ypixel = packet_get_int();
2129 if (strcmp(s->term, "") == 0) {
2134 /* Allocate a pty and open it. */
2135 debug("Allocating pty.");
2136 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
2142 error("session_pty_req: session %d alloc failed", s->self);
2145 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
2147 /* for SSH1 the tty modes length is not given */
2149 n_bytes = packet_remaining();
2150 tty_parse_modes(s->ttyfd, &n_bytes);
2153 pty_setowner(s->pw, s->tty);
2155 /* Set window size from the packet. */
2156 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
2159 session_proctitle(s);
2164 session_subsystem_req(Session *s)
2169 char *prog, *cmd, *subsys = packet_get_string(&len);
2173 logit("subsystem request for %.100s", subsys);
2175 for (i = 0; i < options.num_subsystems; i++) {
2176 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
2177 prog = options.subsystem_command[i];
2178 cmd = options.subsystem_args[i];
2179 if (!strcmp(INTERNAL_SFTP_NAME, prog)) {
2180 s->is_subsystem = SUBSYSTEM_INT_SFTP;
2181 } else if (stat(prog, &st) < 0) {
2182 error("subsystem: cannot stat %s: %s", prog,
2186 s->is_subsystem = SUBSYSTEM_EXT;
2188 debug("subsystem: exec() %s", cmd);
2196 logit("subsystem request for %.100s failed, subsystem not found",
2204 session_x11_req(Session *s)
2208 if (s->auth_proto != NULL || s->auth_data != NULL) {
2209 error("session_x11_req: session %d: "
2210 "x11 forwarding already active", s->self);
2213 s->single_connection = packet_get_char();
2214 s->auth_proto = packet_get_string(NULL);
2215 s->auth_data = packet_get_string(NULL);
2216 s->screen = packet_get_int();
2219 success = session_setup_x11fwd(s);
2221 xfree(s->auth_proto);
2222 xfree(s->auth_data);
2223 s->auth_proto = NULL;
2224 s->auth_data = NULL;
2230 session_shell_req(Session *s)
2238 session_exec_req(Session *s)
2241 char *command = packet_get_string(&len);
2243 do_exec(s, command);
2249 session_break_req(Session *s)
2252 packet_get_int(); /* ignored */
2255 if (s->ttyfd == -1 ||
2256 tcsendbreak(s->ttyfd, 0) < 0)
2262 session_env_req(Session *s)
2265 u_int name_len, val_len, i;
2267 name = packet_get_string(&name_len);
2268 val = packet_get_string(&val_len);
2271 /* Don't set too many environment variables */
2272 if (s->num_env > 128) {
2273 debug2("Ignoring env request %s: too many env vars", name);
2277 for (i = 0; i < options.num_accept_env; i++) {
2278 if (match_pattern(name, options.accept_env[i])) {
2279 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2280 s->env = xrealloc(s->env, s->num_env + 1,
2282 s->env[s->num_env].name = name;
2283 s->env[s->num_env].val = val;
2288 debug2("Ignoring env request %s: disallowed name", name);
2297 session_auth_agent_req(Session *s)
2299 static int called = 0;
2301 if (no_agent_forwarding_flag) {
2302 debug("session_auth_agent_req: no_agent_forwarding_flag");
2309 return auth_input_request_forwarding(s->pw);
2314 session_input_channel_req(Channel *c, const char *rtype)
2319 if ((s = session_by_channel(c->self)) == NULL) {
2320 logit("session_input_channel_req: no session %d req %.100s",
2324 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2327 * a session is in LARVAL state until a shell, a command
2328 * or a subsystem is executed
2330 if (c->type == SSH_CHANNEL_LARVAL) {
2331 if (strcmp(rtype, "shell") == 0) {
2332 success = session_shell_req(s);
2333 } else if (strcmp(rtype, "exec") == 0) {
2334 success = session_exec_req(s);
2335 } else if (strcmp(rtype, "pty-req") == 0) {
2336 success = session_pty_req(s);
2337 } else if (strcmp(rtype, "x11-req") == 0) {
2338 success = session_x11_req(s);
2339 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2340 success = session_auth_agent_req(s);
2341 } else if (strcmp(rtype, "subsystem") == 0) {
2342 success = session_subsystem_req(s);
2343 } else if (strcmp(rtype, "env") == 0) {
2344 success = session_env_req(s);
2347 if (strcmp(rtype, "window-change") == 0) {
2348 success = session_window_change_req(s);
2349 } else if (strcmp(rtype, "break") == 0) {
2350 success = session_break_req(s);
2357 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2360 fatal("session_set_fds: called for proto != 2.0");
2362 * now that have a child and a pipe to the child,
2363 * we can activate our channel and register the fd's
2365 if (s->chanid == -1)
2366 fatal("no channel for session %d", s->self);
2367 if(options.hpn_disabled)
2368 channel_set_fds(s->chanid,
2370 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2372 CHAN_SES_WINDOW_DEFAULT);
2374 channel_set_fds(s->chanid,
2376 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2378 options.hpn_buffer_size);
2382 * Function to perform pty cleanup. Also called if we get aborted abnormally
2383 * (e.g., due to a dropped connection).
2386 session_pty_cleanup2(Session *s)
2389 error("session_pty_cleanup: no session");
2395 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2397 /* Record that the user has logged out. */
2399 record_logout(s->pid, s->tty, s->pw->pw_name);
2401 /* Release the pseudo-tty. */
2403 pty_release(s->tty);
2406 * Close the server side of the socket pairs. We must do this after
2407 * the pty cleanup, so that another process doesn't get this pty
2408 * while we're still cleaning up.
2410 if (close(s->ptymaster) < 0)
2411 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2413 /* unlink pty from session */
2418 session_pty_cleanup(Session *s)
2420 PRIVSEP(session_pty_cleanup2(s));
2426 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2441 return "SIG@openssh.com";
2445 session_close_x11(int id)
2449 if ((c = channel_by_id(id)) == NULL) {
2450 debug("session_close_x11: x11 channel %d missing", id);
2452 /* Detach X11 listener */
2453 debug("session_close_x11: detach x11 channel %d", id);
2454 channel_cancel_cleanup(id);
2455 if (c->ostate != CHAN_OUTPUT_CLOSED)
2461 session_close_single_x11(int id, void *arg)
2466 debug3("session_close_single_x11: channel %d", id);
2467 channel_cancel_cleanup(id);
2468 if ((s = session_by_x11_channel(id)) == NULL)
2469 fatal("session_close_single_x11: no x11 channel %d", id);
2470 for (i = 0; s->x11_chanids[i] != -1; i++) {
2471 debug("session_close_single_x11: session %d: "
2472 "closing channel %d", s->self, s->x11_chanids[i]);
2474 * The channel "id" is already closing, but make sure we
2475 * close all of its siblings.
2477 if (s->x11_chanids[i] != id)
2478 session_close_x11(s->x11_chanids[i]);
2480 xfree(s->x11_chanids);
2481 s->x11_chanids = NULL;
2486 if (s->auth_proto) {
2487 xfree(s->auth_proto);
2488 s->auth_proto = NULL;
2491 xfree(s->auth_data);
2492 s->auth_data = NULL;
2494 if (s->auth_display) {
2495 xfree(s->auth_display);
2496 s->auth_display = NULL;
2501 session_exit_message(Session *s, int status)
2505 if ((c = channel_lookup(s->chanid)) == NULL)
2506 fatal("session_exit_message: session %d: no channel %d",
2507 s->self, s->chanid);
2508 debug("session_exit_message: session %d channel %d pid %ld",
2509 s->self, s->chanid, (long)s->pid);
2511 if (WIFEXITED(status)) {
2512 channel_request_start(s->chanid, "exit-status", 0);
2513 packet_put_int(WEXITSTATUS(status));
2515 } else if (WIFSIGNALED(status)) {
2516 channel_request_start(s->chanid, "exit-signal", 0);
2517 packet_put_cstring(sig2name(WTERMSIG(status)));
2519 packet_put_char(WCOREDUMP(status)? 1 : 0);
2520 #else /* WCOREDUMP */
2522 #endif /* WCOREDUMP */
2523 packet_put_cstring("");
2524 packet_put_cstring("");
2527 /* Some weird exit cause. Just exit. */
2528 packet_disconnect("wait returned status %04x.", status);
2531 /* disconnect channel */
2532 debug("session_exit_message: release channel %d", s->chanid);
2535 * Adjust cleanup callback attachment to send close messages when
2536 * the channel gets EOF. The session will be then be closed
2537 * by session_close_by_channel when the childs close their fds.
2539 channel_register_cleanup(c->self, session_close_by_channel, 1);
2542 * emulate a write failure with 'chan_write_failed', nobody will be
2543 * interested in data we write.
2544 * Note that we must not call 'chan_read_failed', since there could
2545 * be some more data waiting in the pipe.
2547 if (c->ostate != CHAN_OUTPUT_CLOSED)
2548 chan_write_failed(c);
2552 session_close(Session *s)
2556 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2558 session_pty_cleanup(s);
2564 xfree(s->x11_chanids);
2565 if (s->auth_display)
2566 xfree(s->auth_display);
2568 xfree(s->auth_data);
2570 xfree(s->auth_proto);
2572 if (s->env != NULL) {
2573 for (i = 0; i < s->num_env; i++) {
2574 xfree(s->env[i].name);
2575 xfree(s->env[i].val);
2579 session_proctitle(s);
2583 session_close_by_pid(pid_t pid, int status)
2585 Session *s = session_by_pid(pid);
2587 debug("session_close_by_pid: no session for pid %ld",
2591 if (s->chanid != -1)
2592 session_exit_message(s, status);
2594 session_pty_cleanup(s);
2599 * this is called when a channel dies before
2600 * the session 'child' itself dies
2603 session_close_by_channel(int id, void *arg)
2605 Session *s = session_by_channel(id);
2609 debug("session_close_by_channel: no session for id %d", id);
2612 debug("session_close_by_channel: channel %d child %ld",
2615 debug("session_close_by_channel: channel %d: has child", id);
2617 * delay detach of session, but release pty, since
2618 * the fd's to the child are already closed
2621 session_pty_cleanup(s);
2624 /* detach by removing callback */
2625 channel_cancel_cleanup(s->chanid);
2627 /* Close any X11 listeners associated with this session */
2628 if (s->x11_chanids != NULL) {
2629 for (i = 0; s->x11_chanids[i] != -1; i++) {
2630 session_close_x11(s->x11_chanids[i]);
2631 s->x11_chanids[i] = -1;
2640 session_destroy_all(void (*closefunc)(Session *))
2643 for (i = 0; i < MAX_SESSIONS; i++) {
2644 Session *s = &sessions[i];
2646 if (closefunc != NULL)
2655 session_tty_list(void)
2657 static char buf[1024];
2662 for (i = 0; i < MAX_SESSIONS; i++) {
2663 Session *s = &sessions[i];
2664 if (s->used && s->ttyfd != -1) {
2666 if (strncmp(s->tty, "/dev/", 5) != 0) {
2667 cp = strrchr(s->tty, '/');
2668 cp = (cp == NULL) ? s->tty : cp + 1;
2673 strlcat(buf, ",", sizeof buf);
2674 strlcat(buf, cp, sizeof buf);
2678 strlcpy(buf, "notty", sizeof buf);
2683 session_proctitle(Session *s)
2686 error("no user for session %d", s->self);
2688 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2692 session_setup_x11fwd(Session *s)
2695 char display[512], auth_display[512];
2696 char hostname[MAXHOSTNAMELEN];
2699 if (no_x11_forwarding_flag) {
2700 packet_send_debug("X11 forwarding disabled in user configuration file.");
2703 if (!options.x11_forwarding) {
2704 debug("X11 forwarding disabled in server configuration file.");
2707 if (!options.xauth_location ||
2708 (stat(options.xauth_location, &st) == -1)) {
2709 packet_send_debug("No xauth program; cannot forward with spoofing.");
2712 if (options.use_login) {
2713 packet_send_debug("X11 forwarding disabled; "
2714 "not compatible with UseLogin=yes.");
2717 if (s->display != NULL) {
2718 debug("X11 display already set.");
2721 if (x11_create_display_inet(options.x11_display_offset,
2722 options.x11_use_localhost, s->single_connection,
2723 &s->display_number, &s->x11_chanids,
2724 options.hpn_disabled, options.hpn_buffer_size) == -1) {
2725 debug("x11_create_display_inet failed.");
2728 for (i = 0; s->x11_chanids[i] != -1; i++) {
2729 channel_register_cleanup(s->x11_chanids[i],
2730 session_close_single_x11, 0);
2733 /* Set up a suitable value for the DISPLAY variable. */
2734 if (gethostname(hostname, sizeof(hostname)) < 0)
2735 fatal("gethostname: %.100s", strerror(errno));
2737 * auth_display must be used as the displayname when the
2738 * authorization entry is added with xauth(1). This will be
2739 * different than the DISPLAY string for localhost displays.
2741 if (options.x11_use_localhost) {
2742 snprintf(display, sizeof display, "localhost:%u.%u",
2743 s->display_number, s->screen);
2744 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2745 s->display_number, s->screen);
2746 s->display = xstrdup(display);
2747 s->auth_display = xstrdup(auth_display);
2749 #ifdef IPADDR_IN_DISPLAY
2751 struct in_addr my_addr;
2753 he = gethostbyname(hostname);
2755 error("Can't get IP address for X11 DISPLAY.");
2756 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2759 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2760 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2761 s->display_number, s->screen);
2763 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2764 s->display_number, s->screen);
2766 s->display = xstrdup(display);
2767 s->auth_display = xstrdup(display);
2774 do_authenticated2(Authctxt *authctxt)
2776 server_loop2(authctxt);
2780 do_cleanup(Authctxt *authctxt)
2782 static int called = 0;
2784 debug("do_cleanup");
2786 /* no cleanup if we're in the child for login shell */
2790 /* avoid double cleanup */
2795 if (authctxt == NULL)
2799 if (options.use_pam) {
2801 sshpam_thread_cleanup();
2805 if (!authctxt->authenticated)
2809 if (options.kerberos_ticket_cleanup &&
2811 krb5_cleanup_proc(authctxt);
2815 if (compat20 && options.gss_cleanup_creds)
2816 ssh_gssapi_cleanup_creds();
2819 /* remove agent socket */
2820 auth_sock_cleanup_proc(authctxt->pw);
2823 * Cleanup ptys/utmp only if privsep is disabled,
2824 * or if running in monitor.
2826 if (!use_privsep || mm_is_monitor())
2827 session_destroy_all(session_pty_cleanup2);