1 /* $OpenBSD: session.c,v 1.217 2006/08/04 20:46:05 stevesk 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>
79 #include "auth-options.h"
80 #include "pathnames.h"
84 #include "serverloop.h"
88 #include "monitor_wrap.h"
90 #if defined(KRB5) && defined(USE_AFS)
96 Session
*session_new(void);
97 void session_set_fds(Session
*, int, int, int);
98 void session_pty_cleanup(Session
*);
99 void session_proctitle(Session
*);
100 int session_setup_x11fwd(Session
*);
101 void do_exec_pty(Session
*, const char *);
102 void do_exec_no_pty(Session
*, const char *);
103 void do_exec(Session
*, const char *);
104 void do_login(Session
*, const char *);
105 #ifdef LOGIN_NEEDS_UTMPX
106 static void do_pre_login(Session
*s
);
108 void do_child(Session
*, const char *);
110 int check_quietlogin(Session
*, const char *);
112 static void do_authenticated1(Authctxt
*);
113 static void do_authenticated2(Authctxt
*);
115 static int session_pty_req(Session
*);
118 extern ServerOptions options
;
119 extern char *__progname
;
120 extern int log_stderr
;
121 extern int debug_flag
;
122 extern u_int utmp_len
;
123 extern int startup_pipe
;
124 extern void destroy_sensitive_data(void);
125 extern Buffer loginmsg
;
127 /* original command from peer. */
128 const char *original_command
= NULL
;
131 #define MAX_SESSIONS 10
132 Session sessions
[MAX_SESSIONS
];
134 #ifdef HAVE_LOGIN_CAP
138 static int is_child
= 0;
140 /* Name and directory of socket for authentication agent forwarding. */
141 static char *auth_sock_name
= NULL
;
142 static char *auth_sock_dir
= NULL
;
144 /* removes the agent forwarding socket */
147 auth_sock_cleanup_proc(struct passwd
*pw
)
149 if (auth_sock_name
!= NULL
) {
150 temporarily_use_uid(pw
);
151 unlink(auth_sock_name
);
152 rmdir(auth_sock_dir
);
153 auth_sock_name
= NULL
;
159 auth_input_request_forwarding(struct passwd
* pw
)
163 struct sockaddr_un sunaddr
;
165 if (auth_sock_name
!= NULL
) {
166 error("authentication forwarding requested twice.");
170 /* Temporarily drop privileged uid for mkdir/bind. */
171 temporarily_use_uid(pw
);
173 /* Allocate a buffer for the socket name, and format the name. */
174 auth_sock_name
= xmalloc(MAXPATHLEN
);
175 auth_sock_dir
= xmalloc(MAXPATHLEN
);
176 strlcpy(auth_sock_dir
, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN
);
178 /* Create private directory for socket */
179 if (mkdtemp(auth_sock_dir
) == NULL
) {
180 packet_send_debug("Agent forwarding disabled: "
181 "mkdtemp() failed: %.100s", strerror(errno
));
183 xfree(auth_sock_name
);
184 xfree(auth_sock_dir
);
185 auth_sock_name
= NULL
;
186 auth_sock_dir
= NULL
;
189 snprintf(auth_sock_name
, MAXPATHLEN
, "%s/agent.%ld",
190 auth_sock_dir
, (long) getpid());
192 /* Create the socket. */
193 sock
= socket(AF_UNIX
, SOCK_STREAM
, 0);
195 packet_disconnect("socket: %.100s", strerror(errno
));
197 /* Bind it to the name. */
198 memset(&sunaddr
, 0, sizeof(sunaddr
));
199 sunaddr
.sun_family
= AF_UNIX
;
200 strlcpy(sunaddr
.sun_path
, auth_sock_name
, sizeof(sunaddr
.sun_path
));
202 if (bind(sock
, (struct sockaddr
*)&sunaddr
, sizeof(sunaddr
)) < 0)
203 packet_disconnect("bind: %.100s", strerror(errno
));
205 /* Restore the privileged uid. */
208 /* Start listening on the socket. */
209 if (listen(sock
, SSH_LISTEN_BACKLOG
) < 0)
210 packet_disconnect("listen: %.100s", strerror(errno
));
212 /* Allocate a channel for the authentication agent socket. */
213 nc
= channel_new("auth socket",
214 SSH_CHANNEL_AUTH_SOCKET
, sock
, sock
, -1,
215 CHAN_X11_WINDOW_DEFAULT
, CHAN_X11_PACKET_DEFAULT
,
216 0, "auth socket", 1);
217 strlcpy(nc
->path
, auth_sock_name
, sizeof(nc
->path
));
222 display_loginmsg(void)
224 if (buffer_len(&loginmsg
) > 0) {
225 buffer_append(&loginmsg
, "\0", 1);
226 printf("%s", (char *)buffer_ptr(&loginmsg
));
227 buffer_clear(&loginmsg
);
232 do_authenticated(Authctxt
*authctxt
)
234 setproctitle("%s", authctxt
->pw
->pw_name
);
236 /* setup the channel layer */
237 if (!no_port_forwarding_flag
&& options
.allow_tcp_forwarding
)
238 channel_permit_all_opens();
241 do_authenticated2(authctxt
);
243 do_authenticated1(authctxt
);
245 do_cleanup(authctxt
);
249 * Prepares for an interactive session. This is called after the user has
250 * been successfully authenticated. During this message exchange, pseudo
251 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
252 * are requested, etc.
255 do_authenticated1(Authctxt
*authctxt
)
259 int success
, type
, screen_flag
;
260 int enable_compression_after_reply
= 0;
261 u_int proto_len
, data_len
, dlen
, compression_level
= 0;
265 error("no more sessions");
268 s
->authctxt
= authctxt
;
269 s
->pw
= authctxt
->pw
;
272 * We stay in this loop until the client requests to execute a shell
278 /* Get a packet from the client. */
279 type
= packet_read();
281 /* Process the packet. */
283 case SSH_CMSG_REQUEST_COMPRESSION
:
284 compression_level
= packet_get_int();
286 if (compression_level
< 1 || compression_level
> 9) {
287 packet_send_debug("Received invalid compression level %d.",
291 if (options
.compression
== COMP_NONE
) {
292 debug2("compression disabled");
295 /* Enable compression after we have responded with SUCCESS. */
296 enable_compression_after_reply
= 1;
300 case SSH_CMSG_REQUEST_PTY
:
301 success
= session_pty_req(s
);
304 case SSH_CMSG_X11_REQUEST_FORWARDING
:
305 s
->auth_proto
= packet_get_string(&proto_len
);
306 s
->auth_data
= packet_get_string(&data_len
);
308 screen_flag
= packet_get_protocol_flags() &
309 SSH_PROTOFLAG_SCREEN_NUMBER
;
310 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag
);
312 if (packet_remaining() == 4) {
314 debug2("Buggy client: "
315 "X11 screen flag missing");
316 s
->screen
= packet_get_int();
321 success
= session_setup_x11fwd(s
);
323 xfree(s
->auth_proto
);
325 s
->auth_proto
= NULL
;
330 case SSH_CMSG_AGENT_REQUEST_FORWARDING
:
331 if (no_agent_forwarding_flag
|| compat13
) {
332 debug("Authentication agent forwarding not permitted for this authentication.");
335 debug("Received authentication agent forwarding request.");
336 success
= auth_input_request_forwarding(s
->pw
);
339 case SSH_CMSG_PORT_FORWARD_REQUEST
:
340 if (no_port_forwarding_flag
) {
341 debug("Port forwarding not permitted for this authentication.");
344 if (!options
.allow_tcp_forwarding
) {
345 debug("Port forwarding not permitted.");
348 debug("Received TCP/IP port forwarding request.");
349 if (channel_input_port_forward_request(s
->pw
->pw_uid
== 0,
350 options
.gateway_ports
) < 0) {
351 debug("Port forwarding failed.");
357 case SSH_CMSG_MAX_PACKET_SIZE
:
358 if (packet_set_maxsize(packet_get_int()) > 0)
362 case SSH_CMSG_EXEC_SHELL
:
363 case SSH_CMSG_EXEC_CMD
:
364 if (type
== SSH_CMSG_EXEC_CMD
) {
365 command
= packet_get_string(&dlen
);
366 debug("Exec command '%.500s'", command
);
378 * Any unknown messages in this phase are ignored,
379 * and a failure message is returned.
381 logit("Unknown packet type received after authentication: %d", type
);
383 packet_start(success
? SSH_SMSG_SUCCESS
: SSH_SMSG_FAILURE
);
387 /* Enable compression now that we have replied if appropriate. */
388 if (enable_compression_after_reply
) {
389 enable_compression_after_reply
= 0;
390 packet_start_compression(compression_level
);
396 * This is called to fork and execute a command when we have no tty. This
397 * will call do_child from the child, and server_loop from the parent after
398 * setting up file descriptors and such.
401 do_exec_no_pty(Session
*s
, const char *command
)
406 int pin
[2], pout
[2], perr
[2];
407 /* Allocate pipes for communicating with the program. */
408 if (pipe(pin
) < 0 || pipe(pout
) < 0 || pipe(perr
) < 0)
409 packet_disconnect("Could not create pipes: %.100s",
411 #else /* USE_PIPES */
412 int inout
[2], err
[2];
413 /* Uses socket pairs to communicate with the program. */
414 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, inout
) < 0 ||
415 socketpair(AF_UNIX
, SOCK_STREAM
, 0, err
) < 0)
416 packet_disconnect("Could not create socket pairs: %.100s",
418 #endif /* USE_PIPES */
420 fatal("do_exec_no_pty: no session");
422 session_proctitle(s
);
425 if (options
.use_pam
&& !use_privsep
)
429 /* Fork the child. */
430 if ((pid
= fork()) == 0) {
433 /* Child. Reinitialize the log since the pid has changed. */
434 log_init(__progname
, options
.log_level
, options
.log_facility
, log_stderr
);
437 * Create a new session and process group since the 4.4BSD
438 * setlogin() affects the entire process group.
441 error("setsid failed: %.100s", strerror(errno
));
445 * Redirect stdin. We close the parent side of the socket
446 * pair, and make the child side the standard input.
449 if (dup2(pin
[0], 0) < 0)
450 perror("dup2 stdin");
453 /* Redirect stdout. */
455 if (dup2(pout
[1], 1) < 0)
456 perror("dup2 stdout");
459 /* Redirect stderr. */
461 if (dup2(perr
[1], 2) < 0)
462 perror("dup2 stderr");
464 #else /* USE_PIPES */
466 * Redirect stdin, stdout, and stderr. Stdin and stdout will
467 * use the same socket, as some programs (particularly rdist)
468 * seem to depend on it.
472 if (dup2(inout
[0], 0) < 0) /* stdin */
473 perror("dup2 stdin");
474 if (dup2(inout
[0], 1) < 0) /* stdout. Note: same socket as stdin. */
475 perror("dup2 stdout");
476 if (dup2(err
[0], 2) < 0) /* stderr */
477 perror("dup2 stderr");
478 #endif /* USE_PIPES */
481 cray_init_job(s
->pw
); /* set up cray jid and tmpdir */
484 /* Do processing for the child (exec command etc). */
485 do_child(s
, command
);
489 signal(WJSIGNAL
, cray_job_termination_handler
);
493 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE
);
496 packet_disconnect("fork failed: %.100s", strerror(errno
));
498 /* Set interactive/non-interactive mode. */
499 packet_set_interactive(s
->display
!= NULL
);
501 /* We are the parent. Close the child sides of the pipes. */
507 if (s
->is_subsystem
) {
511 session_set_fds(s
, pin
[1], pout
[0], perr
[0]);
513 /* Enter the interactive session. */
514 server_loop(pid
, pin
[1], pout
[0], perr
[0]);
515 /* server_loop has closed pin[1], pout[0], and perr[0]. */
517 #else /* USE_PIPES */
518 /* We are the parent. Close the child sides of the socket pairs. */
523 * Clear loginmsg, since it's the child's responsibility to display
524 * it to the user, otherwise multiple sessions may accumulate
525 * multiple copies of the login messages.
527 buffer_clear(&loginmsg
);
530 * Enter the interactive session. Note: server_loop must be able to
531 * handle the case that fdin and fdout are the same.
534 session_set_fds(s
, inout
[1], inout
[1], s
->is_subsystem
? -1 : err
[1]);
536 server_loop(pid
, inout
[1], inout
[1], err
[1]);
537 /* server_loop has closed inout[1] and err[1]. */
539 #endif /* USE_PIPES */
543 * This is called to fork and execute a command when we have a tty. This
544 * will call do_child from the child, and server_loop from the parent after
545 * setting up file descriptors, controlling tty, updating wtmp, utmp,
546 * lastlog, and other such operations.
549 do_exec_pty(Session
*s
, const char *command
)
551 int fdout
, ptyfd
, ttyfd
, ptymaster
;
555 fatal("do_exec_pty: no session");
560 if (options
.use_pam
) {
561 do_pam_set_tty(s
->tty
);
567 /* Fork the child. */
568 if ((pid
= fork()) == 0) {
571 /* Child. Reinitialize the log because the pid has changed. */
572 log_init(__progname
, options
.log_level
, options
.log_facility
, log_stderr
);
573 /* Close the master side of the pseudo tty. */
576 /* Make the pseudo tty our controlling tty. */
577 pty_make_controlling_tty(&ttyfd
, s
->tty
);
579 /* Redirect stdin/stdout/stderr from the pseudo tty. */
580 if (dup2(ttyfd
, 0) < 0)
581 error("dup2 stdin: %s", strerror(errno
));
582 if (dup2(ttyfd
, 1) < 0)
583 error("dup2 stdout: %s", strerror(errno
));
584 if (dup2(ttyfd
, 2) < 0)
585 error("dup2 stderr: %s", strerror(errno
));
587 /* Close the extra descriptor for the pseudo tty. */
590 /* record login, etc. similar to login(1) */
592 if (!(options
.use_login
&& command
== NULL
)) {
594 cray_init_job(s
->pw
); /* set up cray jid and tmpdir */
596 do_login(s
, command
);
598 # ifdef LOGIN_NEEDS_UTMPX
604 /* Do common processing for the child, such as execing the command. */
605 do_child(s
, command
);
609 signal(WJSIGNAL
, cray_job_termination_handler
);
613 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE
);
616 packet_disconnect("fork failed: %.100s", strerror(errno
));
619 /* Parent. Close the slave side of the pseudo tty. */
623 * Create another descriptor of the pty master side for use as the
624 * standard input. We could use the original descriptor, but this
625 * simplifies code in server_loop. The descriptor is bidirectional.
629 packet_disconnect("dup #1 failed: %.100s", strerror(errno
));
631 /* we keep a reference to the pty master */
632 ptymaster
= dup(ptyfd
);
634 packet_disconnect("dup #2 failed: %.100s", strerror(errno
));
635 s
->ptymaster
= ptymaster
;
637 /* Enter interactive session. */
638 packet_set_interactive(1);
640 session_set_fds(s
, ptyfd
, fdout
, -1);
642 server_loop(pid
, ptyfd
, fdout
, -1);
643 /* server_loop _has_ closed ptyfd and fdout. */
647 #ifdef LOGIN_NEEDS_UTMPX
649 do_pre_login(Session
*s
)
652 struct sockaddr_storage from
;
653 pid_t pid
= getpid();
656 * Get IP address of client. If the connection is not a socket, let
657 * the address be 0.0.0.0.
659 memset(&from
, 0, sizeof(from
));
660 fromlen
= sizeof(from
);
661 if (packet_connection_is_on_socket()) {
662 if (getpeername(packet_get_connection_in(),
663 (struct sockaddr
*)&from
, &fromlen
) < 0) {
664 debug("getpeername: %.100s", strerror(errno
));
669 record_utmp_only(pid
, s
->tty
, s
->pw
->pw_name
,
670 get_remote_name_or_ip(utmp_len
, options
.use_dns
),
671 (struct sockaddr
*)&from
, fromlen
);
676 * This is called to fork and execute a command. If another command is
677 * to be forced, execute that instead.
680 do_exec(Session
*s
, const char *command
)
682 if (options
.adm_forced_command
) {
683 original_command
= command
;
684 command
= options
.adm_forced_command
;
685 debug("Forced command (config) '%.900s'", command
);
686 } else if (forced_command
) {
687 original_command
= command
;
688 command
= forced_command
;
689 debug("Forced command (key option) '%.900s'", command
);
692 #ifdef SSH_AUDIT_EVENTS
694 PRIVSEP(audit_run_command(command
));
695 else if (s
->ttyfd
== -1) {
696 char *shell
= s
->pw
->pw_shell
;
698 if (shell
[0] == '\0') /* empty shell means /bin/sh */
700 PRIVSEP(audit_run_command(shell
));
705 do_exec_pty(s
, command
);
707 do_exec_no_pty(s
, command
);
709 original_command
= NULL
;
712 * Clear loginmsg: it's the child's responsibility to display
713 * it to the user, otherwise multiple sessions may accumulate
714 * multiple copies of the login messages.
716 buffer_clear(&loginmsg
);
719 /* administrative, login(1)-like work */
721 do_login(Session
*s
, const char *command
)
724 struct sockaddr_storage from
;
725 struct passwd
* pw
= s
->pw
;
726 pid_t pid
= getpid();
729 * Get IP address of client. If the connection is not a socket, let
730 * the address be 0.0.0.0.
732 memset(&from
, 0, sizeof(from
));
733 fromlen
= sizeof(from
);
734 if (packet_connection_is_on_socket()) {
735 if (getpeername(packet_get_connection_in(),
736 (struct sockaddr
*) & from
, &fromlen
) < 0) {
737 debug("getpeername: %.100s", strerror(errno
));
742 /* Record that there was a login on that tty from the remote host. */
744 record_login(pid
, s
->tty
, pw
->pw_name
, pw
->pw_uid
,
745 get_remote_name_or_ip(utmp_len
,
747 (struct sockaddr
*)&from
, fromlen
);
751 * If password change is needed, do it now.
752 * This needs to occur before the ~/.hushlogin check.
754 if (options
.use_pam
&& !use_privsep
&& s
->authctxt
->force_pwchange
) {
757 s
->authctxt
->force_pwchange
= 0;
758 /* XXX - signal [net] parent to enable forwardings */
762 if (check_quietlogin(s
, command
))
771 * Display the message of the day.
779 if (options
.print_motd
) {
780 #ifdef HAVE_LOGIN_CAP
781 f
= fopen(login_getcapstr(lc
, "welcome", "/etc/motd",
784 f
= fopen("/etc/motd", "r");
787 while (fgets(buf
, sizeof(buf
), f
))
796 * Check for quiet login, either .hushlogin or command given.
799 check_quietlogin(Session
*s
, const char *command
)
802 struct passwd
*pw
= s
->pw
;
805 /* Return 1 if .hushlogin exists or a command given. */
808 snprintf(buf
, sizeof(buf
), "%.200s/.hushlogin", pw
->pw_dir
);
809 #ifdef HAVE_LOGIN_CAP
810 if (login_getcapbool(lc
, "hushlogin", 0) || stat(buf
, &st
) >= 0)
813 if (stat(buf
, &st
) >= 0)
820 * Sets the value of the given variable in the environment. If the variable
821 * already exists, its value is overriden.
824 child_set_env(char ***envp
, u_int
*envsizep
, const char *name
,
832 * If we're passed an uninitialized list, allocate a single null
833 * entry before continuing.
835 if (*envp
== NULL
&& *envsizep
== 0) {
836 *envp
= xmalloc(sizeof(char *));
842 * Find the slot where the value should be stored. If the variable
843 * already exists, we reuse the slot; otherwise we append a new slot
844 * at the end of the array, expanding if necessary.
847 namelen
= strlen(name
);
848 for (i
= 0; env
[i
]; i
++)
849 if (strncmp(env
[i
], name
, namelen
) == 0 && env
[i
][namelen
] == '=')
852 /* Reuse the slot. */
855 /* New variable. Expand if necessary. */
857 if (i
>= envsize
- 1) {
859 fatal("child_set_env: too many env vars");
861 env
= (*envp
) = xrealloc(env
, envsize
, sizeof(char *));
864 /* Need to set the NULL pointer at end of array beyond the new slot. */
868 /* Allocate space and format the variable in the appropriate slot. */
869 env
[i
] = xmalloc(strlen(name
) + 1 + strlen(value
) + 1);
870 snprintf(env
[i
], strlen(name
) + 1 + strlen(value
) + 1, "%s=%s", name
, value
);
874 * Reads environment variables from the given file and adds/overrides them
875 * into the environment. If the file does not exist, this does nothing.
876 * Otherwise, it must consist of empty lines, comments (line starts with '#')
877 * and assignments of the form name=value. No other forms are allowed.
880 read_environment_file(char ***env
, u_int
*envsize
,
881 const char *filename
)
888 f
= fopen(filename
, "r");
892 while (fgets(buf
, sizeof(buf
), f
)) {
894 fatal("Too many lines in environment file %s", filename
);
895 for (cp
= buf
; *cp
== ' ' || *cp
== '\t'; cp
++)
897 if (!*cp
|| *cp
== '#' || *cp
== '\n')
899 if (strchr(cp
, '\n'))
900 *strchr(cp
, '\n') = '\0';
901 value
= strchr(cp
, '=');
903 fprintf(stderr
, "Bad line %u in %.100s\n", lineno
,
908 * Replace the equals sign by nul, and advance value to
913 child_set_env(env
, envsize
, cp
, value
);
918 #ifdef HAVE_ETC_DEFAULT_LOGIN
920 * Return named variable from specified environment, or NULL if not present.
923 child_get_env(char **env
, const char *name
)
929 for (i
=0; env
[i
] != NULL
; i
++)
930 if (strncmp(name
, env
[i
], len
) == 0 && env
[i
][len
] == '=')
931 return(env
[i
] + len
+ 1);
936 * Read /etc/default/login.
937 * We pick up the PATH (or SUPATH for root) and UMASK.
940 read_etc_default_login(char ***env
, u_int
*envsize
, uid_t uid
)
942 char **tmpenv
= NULL
, *var
;
943 u_int i
, tmpenvsize
= 0;
947 * We don't want to copy the whole file to the child's environment,
948 * so we use a temporary environment and copy the variables we're
951 read_environment_file(&tmpenv
, &tmpenvsize
, "/etc/default/login");
957 var
= child_get_env(tmpenv
, "SUPATH");
959 var
= child_get_env(tmpenv
, "PATH");
961 child_set_env(env
, envsize
, "PATH", var
);
963 if ((var
= child_get_env(tmpenv
, "UMASK")) != NULL
)
964 if (sscanf(var
, "%5lo", &mask
) == 1)
967 for (i
= 0; tmpenv
[i
] != NULL
; i
++)
971 #endif /* HAVE_ETC_DEFAULT_LOGIN */
974 copy_environment(char **source
, char ***env
, u_int
*envsize
)
976 char *var_name
, *var_val
;
982 for(i
= 0; source
[i
] != NULL
; i
++) {
983 var_name
= xstrdup(source
[i
]);
984 if ((var_val
= strstr(var_name
, "=")) == NULL
) {
990 debug3("Copy environment: %s=%s", var_name
, var_val
);
991 child_set_env(env
, envsize
, var_name
, var_val
);
998 do_setup_env(Session
*s
, const char *shell
)
1003 struct passwd
*pw
= s
->pw
;
1004 #ifndef HAVE_LOGIN_CAP
1008 /* Initialize the environment. */
1010 env
= xcalloc(envsize
, sizeof(char *));
1015 * The Windows environment contains some setting which are
1016 * important for a running system. They must not be dropped.
1021 p
= fetch_windows_environment();
1022 copy_environment(p
, &env
, &envsize
);
1023 free_windows_environment(p
);
1028 /* Allow any GSSAPI methods that we've used to alter
1029 * the childs environment as they see fit
1031 ssh_gssapi_do_child(&env
, &envsize
);
1034 if (!options
.use_login
) {
1035 /* Set basic environment. */
1036 for (i
= 0; i
< s
->num_env
; i
++)
1037 child_set_env(&env
, &envsize
, s
->env
[i
].name
,
1040 child_set_env(&env
, &envsize
, "USER", pw
->pw_name
);
1041 child_set_env(&env
, &envsize
, "LOGNAME", pw
->pw_name
);
1043 child_set_env(&env
, &envsize
, "LOGIN", pw
->pw_name
);
1045 child_set_env(&env
, &envsize
, "HOME", pw
->pw_dir
);
1046 #ifdef HAVE_LOGIN_CAP
1047 if (setusercontext(lc
, pw
, pw
->pw_uid
, LOGIN_SETPATH
) < 0)
1048 child_set_env(&env
, &envsize
, "PATH", _PATH_STDPATH
);
1050 child_set_env(&env
, &envsize
, "PATH", getenv("PATH"));
1051 #else /* HAVE_LOGIN_CAP */
1052 # ifndef HAVE_CYGWIN
1054 * There's no standard path on Windows. The path contains
1055 * important components pointing to the system directories,
1056 * needed for loading shared libraries. So the path better
1057 * remains intact here.
1059 # ifdef HAVE_ETC_DEFAULT_LOGIN
1060 read_etc_default_login(&env
, &envsize
, pw
->pw_uid
);
1061 path
= child_get_env(env
, "PATH");
1062 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1063 if (path
== NULL
|| *path
== '\0') {
1064 child_set_env(&env
, &envsize
, "PATH",
1065 s
->pw
->pw_uid
== 0 ?
1066 SUPERUSER_PATH
: _PATH_STDPATH
);
1068 # endif /* HAVE_CYGWIN */
1069 #endif /* HAVE_LOGIN_CAP */
1071 snprintf(buf
, sizeof buf
, "%.200s/%.50s",
1072 _PATH_MAILDIR
, pw
->pw_name
);
1073 child_set_env(&env
, &envsize
, "MAIL", buf
);
1075 /* Normal systems set SHELL by default. */
1076 child_set_env(&env
, &envsize
, "SHELL", shell
);
1079 child_set_env(&env
, &envsize
, "TZ", getenv("TZ"));
1081 /* Set custom environment options from RSA authentication. */
1082 if (!options
.use_login
) {
1083 while (custom_environment
) {
1084 struct envstring
*ce
= custom_environment
;
1087 for (i
= 0; str
[i
] != '=' && str
[i
]; i
++)
1089 if (str
[i
] == '=') {
1091 child_set_env(&env
, &envsize
, str
, str
+ i
+ 1);
1093 custom_environment
= ce
->next
;
1099 /* SSH_CLIENT deprecated */
1100 snprintf(buf
, sizeof buf
, "%.50s %d %d",
1101 get_remote_ipaddr(), get_remote_port(), get_local_port());
1102 child_set_env(&env
, &envsize
, "SSH_CLIENT", buf
);
1104 laddr
= get_local_ipaddr(packet_get_connection_in());
1105 snprintf(buf
, sizeof buf
, "%.50s %d %.50s %d",
1106 get_remote_ipaddr(), get_remote_port(), laddr
, get_local_port());
1108 child_set_env(&env
, &envsize
, "SSH_CONNECTION", buf
);
1111 child_set_env(&env
, &envsize
, "SSH_TTY", s
->tty
);
1113 child_set_env(&env
, &envsize
, "TERM", s
->term
);
1115 child_set_env(&env
, &envsize
, "DISPLAY", s
->display
);
1116 if (original_command
)
1117 child_set_env(&env
, &envsize
, "SSH_ORIGINAL_COMMAND",
1121 if (cray_tmpdir
[0] != '\0')
1122 child_set_env(&env
, &envsize
, "TMPDIR", cray_tmpdir
);
1123 #endif /* _UNICOS */
1126 * Since we clear KRB5CCNAME at startup, if it's set now then it
1127 * must have been set by a native authentication method (eg AIX or
1128 * SIA), so copy it to the child.
1133 if ((cp
= getenv("KRB5CCNAME")) != NULL
)
1134 child_set_env(&env
, &envsize
, "KRB5CCNAME", cp
);
1141 if ((cp
= getenv("AUTHSTATE")) != NULL
)
1142 child_set_env(&env
, &envsize
, "AUTHSTATE", cp
);
1143 read_environment_file(&env
, &envsize
, "/etc/environment");
1147 if (s
->authctxt
->krb5_ccname
)
1148 child_set_env(&env
, &envsize
, "KRB5CCNAME",
1149 s
->authctxt
->krb5_ccname
);
1153 * Pull in any environment variables that may have
1156 if (options
.use_pam
) {
1159 p
= fetch_pam_child_environment();
1160 copy_environment(p
, &env
, &envsize
);
1161 free_pam_environment(p
);
1163 p
= fetch_pam_environment();
1164 copy_environment(p
, &env
, &envsize
);
1165 free_pam_environment(p
);
1167 #endif /* USE_PAM */
1169 if (auth_sock_name
!= NULL
)
1170 child_set_env(&env
, &envsize
, SSH_AUTHSOCKET_ENV_NAME
,
1173 /* read $HOME/.ssh/environment. */
1174 if (options
.permit_user_env
&& !options
.use_login
) {
1175 snprintf(buf
, sizeof buf
, "%.200s/.ssh/environment",
1176 strcmp(pw
->pw_dir
, "/") ? pw
->pw_dir
: "");
1177 read_environment_file(&env
, &envsize
, buf
);
1180 /* dump the environment */
1181 fprintf(stderr
, "Environment:\n");
1182 for (i
= 0; env
[i
]; i
++)
1183 fprintf(stderr
, " %.200s\n", env
[i
]);
1189 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1190 * first in this order).
1193 do_rc_files(Session
*s
, const char *shell
)
1201 s
->display
!= NULL
&& s
->auth_proto
!= NULL
&& s
->auth_data
!= NULL
;
1203 /* ignore _PATH_SSH_USER_RC for subsystems */
1204 if (!s
->is_subsystem
&& (stat(_PATH_SSH_USER_RC
, &st
) >= 0)) {
1205 snprintf(cmd
, sizeof cmd
, "%s -c '%s %s'",
1206 shell
, _PATH_BSHELL
, _PATH_SSH_USER_RC
);
1208 fprintf(stderr
, "Running %s\n", cmd
);
1209 f
= popen(cmd
, "w");
1212 fprintf(f
, "%s %s\n", s
->auth_proto
,
1216 fprintf(stderr
, "Could not run %s\n",
1218 } else if (stat(_PATH_SSH_SYSTEM_RC
, &st
) >= 0) {
1220 fprintf(stderr
, "Running %s %s\n", _PATH_BSHELL
,
1221 _PATH_SSH_SYSTEM_RC
);
1222 f
= popen(_PATH_BSHELL
" " _PATH_SSH_SYSTEM_RC
, "w");
1225 fprintf(f
, "%s %s\n", s
->auth_proto
,
1229 fprintf(stderr
, "Could not run %s\n",
1230 _PATH_SSH_SYSTEM_RC
);
1231 } else if (do_xauth
&& options
.xauth_location
!= NULL
) {
1232 /* Add authority data to .Xauthority if appropriate. */
1235 "Running %.500s remove %.100s\n",
1236 options
.xauth_location
, s
->auth_display
);
1238 "%.500s add %.100s %.100s %.100s\n",
1239 options
.xauth_location
, s
->auth_display
,
1240 s
->auth_proto
, s
->auth_data
);
1242 snprintf(cmd
, sizeof cmd
, "%s -q -",
1243 options
.xauth_location
);
1244 f
= popen(cmd
, "w");
1246 fprintf(f
, "remove %s\n",
1248 fprintf(f
, "add %s %s %s\n",
1249 s
->auth_display
, s
->auth_proto
,
1253 fprintf(stderr
, "Could not run %s\n",
1260 do_nologin(struct passwd
*pw
)
1265 #ifdef HAVE_LOGIN_CAP
1266 if (!login_getcapbool(lc
, "ignorenologin", 0) && pw
->pw_uid
)
1267 f
= fopen(login_getcapstr(lc
, "nologin", _PATH_NOLOGIN
,
1268 _PATH_NOLOGIN
), "r");
1271 f
= fopen(_PATH_NOLOGIN
, "r");
1274 /* /etc/nologin exists. Print its contents and exit. */
1275 logit("User %.100s not allowed because %s exists",
1276 pw
->pw_name
, _PATH_NOLOGIN
);
1277 while (fgets(buf
, sizeof(buf
), f
))
1285 /* Set login name, uid, gid, and groups. */
1287 do_setusercontext(struct passwd
*pw
)
1290 if (getuid() == 0 || geteuid() == 0)
1291 #endif /* HAVE_CYGWIN */
1294 #ifdef HAVE_SETPCRED
1295 if (setpcred(pw
->pw_name
, (char **)NULL
) == -1)
1296 fatal("Failed to set process credentials");
1297 #endif /* HAVE_SETPCRED */
1298 #ifdef HAVE_LOGIN_CAP
1303 if (options
.gss_authentication
) {
1304 temporarily_use_uid(pw
);
1305 ssh_gssapi_storecreds();
1310 if (options
.use_pam
) {
1314 # endif /* USE_PAM */
1315 if (setusercontext(lc
, pw
, pw
->pw_uid
,
1316 (LOGIN_SETALL
& ~LOGIN_SETPATH
)) < 0) {
1317 perror("unable to set user context");
1321 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1322 /* Sets login uid for accounting */
1323 if (getluid() == -1 && setluid(pw
->pw_uid
) == -1)
1324 error("setluid: %s", strerror(errno
));
1325 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1327 if (setlogin(pw
->pw_name
) < 0)
1328 error("setlogin failed: %s", strerror(errno
));
1329 if (setgid(pw
->pw_gid
) < 0) {
1333 /* Initialize the group list. */
1334 if (initgroups(pw
->pw_name
, pw
->pw_gid
) < 0) {
1335 perror("initgroups");
1340 if (options
.gss_authentication
) {
1341 temporarily_use_uid(pw
);
1342 ssh_gssapi_storecreds();
1348 * PAM credentials may take the form of supplementary groups.
1349 * These will have been wiped by the above initgroups() call.
1350 * Reestablish them here.
1352 if (options
.use_pam
) {
1356 # endif /* USE_PAM */
1357 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1358 irix_setusercontext(pw
);
1359 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1363 #if defined(HAVE_LIBIAF) && !defined(BROKEN_LIBIAF)
1364 if (set_id(pw
->pw_name
) != 0) {
1367 #endif /* HAVE_LIBIAF && !BROKEN_LIBIAF */
1368 /* Permanently switch to the desired uid. */
1369 permanently_set_uid(pw
);
1376 if (getuid() != pw
->pw_uid
|| geteuid() != pw
->pw_uid
)
1377 fatal("Failed to set uids to %u.", (u_int
) pw
->pw_uid
);
1380 ssh_selinux_setup_exec_context(pw
->pw_name
);
1385 do_pwchange(Session
*s
)
1388 fprintf(stderr
, "WARNING: Your password has expired.\n");
1389 if (s
->ttyfd
!= -1) {
1391 "You must change your password now and login again!\n");
1392 #ifdef PASSWD_NEEDS_USERNAME
1393 execl(_PATH_PASSWD_PROG
, "passwd", s
->pw
->pw_name
,
1396 execl(_PATH_PASSWD_PROG
, "passwd", (char *)NULL
);
1401 "Password change required but no TTY available.\n");
1407 launch_login(struct passwd
*pw
, const char *hostname
)
1409 /* Launch login(1). */
1411 execl(LOGIN_PROGRAM
, "login", "-h", hostname
,
1412 #ifdef xxxLOGIN_NEEDS_TERM
1413 (s
->term
? s
->term
: "unknown"),
1414 #endif /* LOGIN_NEEDS_TERM */
1415 #ifdef LOGIN_NO_ENDOPT
1416 "-p", "-f", pw
->pw_name
, (char *)NULL
);
1418 "-p", "-f", "--", pw
->pw_name
, (char *)NULL
);
1421 /* Login couldn't be executed, die. */
1428 child_close_fds(void)
1432 if (packet_get_connection_in() == packet_get_connection_out())
1433 close(packet_get_connection_in());
1435 close(packet_get_connection_in());
1436 close(packet_get_connection_out());
1439 * Close all descriptors related to channels. They will still remain
1440 * open in the parent.
1442 /* XXX better use close-on-exec? -markus */
1443 channel_close_all();
1446 * Close any extra file descriptors. Note that there may still be
1447 * descriptors left by system functions. They will be closed later.
1452 * Close any extra open file descriptors so that we don't have them
1453 * hanging around in clients. Note that we want to do this after
1454 * initgroups, because at least on Solaris 2.3 it leaves file
1457 for (i
= 3; i
< 64; i
++)
1462 * Performs common processing for the child, such as setting up the
1463 * environment, closing extra file descriptors, setting the user and group
1464 * ids, and executing the command or shell.
1467 do_child(Session
*s
, const char *command
)
1469 extern char **environ
;
1472 const char *shell
, *shell0
, *hostname
= NULL
;
1473 struct passwd
*pw
= s
->pw
;
1475 /* remove hostkey from the child's memory */
1476 destroy_sensitive_data();
1478 /* Force a password change */
1479 if (s
->authctxt
->force_pwchange
) {
1480 do_setusercontext(pw
);
1486 /* login(1) is only called if we execute the login shell */
1487 if (options
.use_login
&& command
!= NULL
)
1488 options
.use_login
= 0;
1491 cray_setup(pw
->pw_uid
, pw
->pw_name
, command
);
1492 #endif /* _UNICOS */
1495 * Login(1) does this as well, and it needs uid 0 for the "-h"
1496 * switch, so we let login(1) to this for us.
1498 if (!options
.use_login
) {
1500 session_setup_sia(pw
, s
->ttyfd
== -1 ? NULL
: s
->tty
);
1501 if (!check_quietlogin(s
, command
))
1503 #else /* HAVE_OSF_SIA */
1504 /* When PAM is enabled we rely on it to do the nologin check */
1505 if (!options
.use_pam
)
1507 do_setusercontext(pw
);
1509 * PAM session modules in do_setusercontext may have
1510 * generated messages, so if this in an interactive
1511 * login then display them too.
1513 if (!check_quietlogin(s
, command
))
1515 #endif /* HAVE_OSF_SIA */
1519 if (options
.use_pam
&& !options
.use_login
&& !is_pam_session_open()) {
1520 debug3("PAM session not opened, exiting");
1527 * Get the shell from the password data. An empty shell field is
1528 * legal, and means /bin/sh.
1530 shell
= (pw
->pw_shell
[0] == '\0') ? _PATH_BSHELL
: pw
->pw_shell
;
1533 * Make sure $SHELL points to the shell from the password file,
1534 * even if shell is overridden from login.conf
1536 env
= do_setup_env(s
, shell
);
1538 #ifdef HAVE_LOGIN_CAP
1539 shell
= login_getcapstr(lc
, "shell", (char *)shell
, (char *)shell
);
1542 /* we have to stash the hostname before we close our socket. */
1543 if (options
.use_login
)
1544 hostname
= get_remote_name_or_ip(utmp_len
,
1547 * Close the connection descriptors; note that this is the child, and
1548 * the server will still have the socket open, and it is important
1549 * that we do not shutdown it. Note that the descriptors cannot be
1550 * closed before building the environment, as we call
1551 * get_remote_ipaddr there.
1556 * Must take new environment into use so that .ssh/rc,
1557 * /etc/ssh/sshrc and xauth are run in the proper environment.
1561 #if defined(KRB5) && defined(USE_AFS)
1563 * At this point, we check to see if AFS is active and if we have
1564 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1565 * if we can (and need to) extend the ticket into an AFS token. If
1566 * we don't do this, we run into potential problems if the user's
1567 * home directory is in AFS and it's not world-readable.
1570 if (options
.kerberos_get_afs_token
&& k_hasafs() &&
1571 (s
->authctxt
->krb5_ctx
!= NULL
)) {
1574 debug("Getting AFS token");
1578 if (k_afs_cell_of_file(pw
->pw_dir
, cell
, sizeof(cell
)) == 0)
1579 krb5_afslog(s
->authctxt
->krb5_ctx
,
1580 s
->authctxt
->krb5_fwd_ccache
, cell
, NULL
);
1582 krb5_afslog_home(s
->authctxt
->krb5_ctx
,
1583 s
->authctxt
->krb5_fwd_ccache
, NULL
, NULL
, pw
->pw_dir
);
1587 /* Change current directory to the user's home directory. */
1588 if (chdir(pw
->pw_dir
) < 0) {
1589 fprintf(stderr
, "Could not chdir to home directory %s: %s\n",
1590 pw
->pw_dir
, strerror(errno
));
1591 #ifdef HAVE_LOGIN_CAP
1592 if (login_getcapbool(lc
, "requirehome", 0))
1597 if (!options
.use_login
)
1598 do_rc_files(s
, shell
);
1600 /* restore SIGPIPE for child */
1601 signal(SIGPIPE
, SIG_DFL
);
1603 if (options
.use_login
) {
1604 launch_login(pw
, hostname
);
1608 /* Get the last component of the shell name. */
1609 if ((shell0
= strrchr(shell
, '/')) != NULL
)
1615 * If we have no command, execute the shell. In this case, the shell
1616 * name to be passed in argv[0] is preceded by '-' to indicate that
1617 * this is a login shell.
1622 /* Start the shell. Set initial character to '-'. */
1625 if (strlcpy(argv0
+ 1, shell0
, sizeof(argv0
) - 1)
1626 >= sizeof(argv0
) - 1) {
1632 /* Execute the shell. */
1635 execve(shell
, argv
, env
);
1637 /* Executing the shell failed. */
1642 * Execute the command using the user's shell. This uses the -c
1643 * option to execute the command.
1645 argv
[0] = (char *) shell0
;
1647 argv
[2] = (char *) command
;
1649 execve(shell
, argv
, env
);
1658 static int did_init
= 0;
1660 debug("session_new: init");
1661 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1662 sessions
[i
].used
= 0;
1666 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1667 Session
*s
= &sessions
[i
];
1669 memset(s
, 0, sizeof(*s
));
1675 s
->x11_chanids
= NULL
;
1676 debug("session_new: session %d", i
);
1687 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1688 Session
*s
= &sessions
[i
];
1689 debug("dump: used %d session %d %p channel %d pid %ld",
1699 session_open(Authctxt
*authctxt
, int chanid
)
1701 Session
*s
= session_new();
1702 debug("session_open: channel %d", chanid
);
1704 error("no more sessions");
1707 s
->authctxt
= authctxt
;
1708 s
->pw
= authctxt
->pw
;
1709 if (s
->pw
== NULL
|| !authctxt
->valid
)
1710 fatal("no user for session %d", s
->self
);
1711 debug("session_open: session %d: link with channel %d", s
->self
, chanid
);
1717 session_by_tty(char *tty
)
1720 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1721 Session
*s
= &sessions
[i
];
1722 if (s
->used
&& s
->ttyfd
!= -1 && strcmp(s
->tty
, tty
) == 0) {
1723 debug("session_by_tty: session %d tty %s", i
, tty
);
1727 debug("session_by_tty: unknown tty %.100s", tty
);
1733 session_by_channel(int id
)
1736 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1737 Session
*s
= &sessions
[i
];
1738 if (s
->used
&& s
->chanid
== id
) {
1739 debug("session_by_channel: session %d channel %d", i
, id
);
1743 debug("session_by_channel: unknown channel %d", id
);
1749 session_by_x11_channel(int id
)
1753 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1754 Session
*s
= &sessions
[i
];
1756 if (s
->x11_chanids
== NULL
|| !s
->used
)
1758 for (j
= 0; s
->x11_chanids
[j
] != -1; j
++) {
1759 if (s
->x11_chanids
[j
] == id
) {
1760 debug("session_by_x11_channel: session %d "
1761 "channel %d", s
->self
, id
);
1766 debug("session_by_x11_channel: unknown channel %d", id
);
1772 session_by_pid(pid_t pid
)
1775 debug("session_by_pid: pid %ld", (long)pid
);
1776 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1777 Session
*s
= &sessions
[i
];
1778 if (s
->used
&& s
->pid
== pid
)
1781 error("session_by_pid: unknown pid %ld", (long)pid
);
1787 session_window_change_req(Session
*s
)
1789 s
->col
= packet_get_int();
1790 s
->row
= packet_get_int();
1791 s
->xpixel
= packet_get_int();
1792 s
->ypixel
= packet_get_int();
1794 pty_change_window_size(s
->ptyfd
, s
->row
, s
->col
, s
->xpixel
, s
->ypixel
);
1799 session_pty_req(Session
*s
)
1805 debug("Allocating a pty not permitted for this authentication.");
1808 if (s
->ttyfd
!= -1) {
1809 packet_disconnect("Protocol error: you already have a pty.");
1813 s
->term
= packet_get_string(&len
);
1816 s
->col
= packet_get_int();
1817 s
->row
= packet_get_int();
1819 s
->row
= packet_get_int();
1820 s
->col
= packet_get_int();
1822 s
->xpixel
= packet_get_int();
1823 s
->ypixel
= packet_get_int();
1825 if (strcmp(s
->term
, "") == 0) {
1830 /* Allocate a pty and open it. */
1831 debug("Allocating pty.");
1832 if (!PRIVSEP(pty_allocate(&s
->ptyfd
, &s
->ttyfd
, s
->tty
, sizeof(s
->tty
)))) {
1838 error("session_pty_req: session %d alloc failed", s
->self
);
1841 debug("session_pty_req: session %d alloc %s", s
->self
, s
->tty
);
1843 /* for SSH1 the tty modes length is not given */
1845 n_bytes
= packet_remaining();
1846 tty_parse_modes(s
->ttyfd
, &n_bytes
);
1849 pty_setowner(s
->pw
, s
->tty
);
1851 /* Set window size from the packet. */
1852 pty_change_window_size(s
->ptyfd
, s
->row
, s
->col
, s
->xpixel
, s
->ypixel
);
1855 session_proctitle(s
);
1860 session_subsystem_req(Session
*s
)
1865 char *prog
, *cmd
, *subsys
= packet_get_string(&len
);
1869 logit("subsystem request for %.100s", subsys
);
1871 for (i
= 0; i
< options
.num_subsystems
; i
++) {
1872 if (strcmp(subsys
, options
.subsystem_name
[i
]) == 0) {
1873 prog
= options
.subsystem_command
[i
];
1874 cmd
= options
.subsystem_args
[i
];
1875 if (stat(prog
, &st
) < 0) {
1876 error("subsystem: cannot stat %s: %s", prog
,
1880 debug("subsystem: exec() %s", cmd
);
1881 s
->is_subsystem
= 1;
1889 logit("subsystem request for %.100s failed, subsystem not found",
1897 session_x11_req(Session
*s
)
1901 if (s
->auth_proto
!= NULL
|| s
->auth_data
!= NULL
) {
1902 error("session_x11_req: session %d: "
1903 "x11 forwarding already active", s
->self
);
1906 s
->single_connection
= packet_get_char();
1907 s
->auth_proto
= packet_get_string(NULL
);
1908 s
->auth_data
= packet_get_string(NULL
);
1909 s
->screen
= packet_get_int();
1912 success
= session_setup_x11fwd(s
);
1914 xfree(s
->auth_proto
);
1915 xfree(s
->auth_data
);
1916 s
->auth_proto
= NULL
;
1917 s
->auth_data
= NULL
;
1923 session_shell_req(Session
*s
)
1931 session_exec_req(Session
*s
)
1934 char *command
= packet_get_string(&len
);
1936 do_exec(s
, command
);
1942 session_break_req(Session
*s
)
1945 packet_get_int(); /* ignored */
1948 if (s
->ttyfd
== -1 ||
1949 tcsendbreak(s
->ttyfd
, 0) < 0)
1955 session_env_req(Session
*s
)
1958 u_int name_len
, val_len
, i
;
1960 name
= packet_get_string(&name_len
);
1961 val
= packet_get_string(&val_len
);
1964 /* Don't set too many environment variables */
1965 if (s
->num_env
> 128) {
1966 debug2("Ignoring env request %s: too many env vars", name
);
1970 for (i
= 0; i
< options
.num_accept_env
; i
++) {
1971 if (match_pattern(name
, options
.accept_env
[i
])) {
1972 debug2("Setting env %d: %s=%s", s
->num_env
, name
, val
);
1973 s
->env
= xrealloc(s
->env
, s
->num_env
+ 1,
1975 s
->env
[s
->num_env
].name
= name
;
1976 s
->env
[s
->num_env
].val
= val
;
1981 debug2("Ignoring env request %s: disallowed name", name
);
1990 session_auth_agent_req(Session
*s
)
1992 static int called
= 0;
1994 if (no_agent_forwarding_flag
) {
1995 debug("session_auth_agent_req: no_agent_forwarding_flag");
2002 return auth_input_request_forwarding(s
->pw
);
2007 session_input_channel_req(Channel
*c
, const char *rtype
)
2012 if ((s
= session_by_channel(c
->self
)) == NULL
) {
2013 logit("session_input_channel_req: no session %d req %.100s",
2017 debug("session_input_channel_req: session %d req %s", s
->self
, rtype
);
2020 * a session is in LARVAL state until a shell, a command
2021 * or a subsystem is executed
2023 if (c
->type
== SSH_CHANNEL_LARVAL
) {
2024 if (strcmp(rtype
, "shell") == 0) {
2025 success
= session_shell_req(s
);
2026 } else if (strcmp(rtype
, "exec") == 0) {
2027 success
= session_exec_req(s
);
2028 } else if (strcmp(rtype
, "pty-req") == 0) {
2029 success
= session_pty_req(s
);
2030 } else if (strcmp(rtype
, "x11-req") == 0) {
2031 success
= session_x11_req(s
);
2032 } else if (strcmp(rtype
, "auth-agent-req@openssh.com") == 0) {
2033 success
= session_auth_agent_req(s
);
2034 } else if (strcmp(rtype
, "subsystem") == 0) {
2035 success
= session_subsystem_req(s
);
2036 } else if (strcmp(rtype
, "env") == 0) {
2037 success
= session_env_req(s
);
2040 if (strcmp(rtype
, "window-change") == 0) {
2041 success
= session_window_change_req(s
);
2042 } else if (strcmp(rtype
, "break") == 0) {
2043 success
= session_break_req(s
);
2050 session_set_fds(Session
*s
, int fdin
, int fdout
, int fderr
)
2053 fatal("session_set_fds: called for proto != 2.0");
2055 * now that have a child and a pipe to the child,
2056 * we can activate our channel and register the fd's
2058 if (s
->chanid
== -1)
2059 fatal("no channel for session %d", s
->self
);
2060 channel_set_fds(s
->chanid
,
2062 fderr
== -1 ? CHAN_EXTENDED_IGNORE
: CHAN_EXTENDED_READ
,
2064 CHAN_SES_WINDOW_DEFAULT
);
2068 * Function to perform pty cleanup. Also called if we get aborted abnormally
2069 * (e.g., due to a dropped connection).
2072 session_pty_cleanup2(Session
*s
)
2075 error("session_pty_cleanup: no session");
2081 debug("session_pty_cleanup: session %d release %s", s
->self
, s
->tty
);
2083 /* Record that the user has logged out. */
2085 record_logout(s
->pid
, s
->tty
, s
->pw
->pw_name
);
2087 /* Release the pseudo-tty. */
2089 pty_release(s
->tty
);
2092 * Close the server side of the socket pairs. We must do this after
2093 * the pty cleanup, so that another process doesn't get this pty
2094 * while we're still cleaning up.
2096 if (close(s
->ptymaster
) < 0)
2097 error("close(s->ptymaster/%d): %s", s
->ptymaster
, strerror(errno
));
2099 /* unlink pty from session */
2104 session_pty_cleanup(Session
*s
)
2106 PRIVSEP(session_pty_cleanup2(s
));
2112 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2127 return "SIG@openssh.com";
2131 session_close_x11(int id
)
2135 if ((c
= channel_by_id(id
)) == NULL
) {
2136 debug("session_close_x11: x11 channel %d missing", id
);
2138 /* Detach X11 listener */
2139 debug("session_close_x11: detach x11 channel %d", id
);
2140 channel_cancel_cleanup(id
);
2141 if (c
->ostate
!= CHAN_OUTPUT_CLOSED
)
2147 session_close_single_x11(int id
, void *arg
)
2152 debug3("session_close_single_x11: channel %d", id
);
2153 channel_cancel_cleanup(id
);
2154 if ((s
= session_by_x11_channel(id
)) == NULL
)
2155 fatal("session_close_single_x11: no x11 channel %d", id
);
2156 for (i
= 0; s
->x11_chanids
[i
] != -1; i
++) {
2157 debug("session_close_single_x11: session %d: "
2158 "closing channel %d", s
->self
, s
->x11_chanids
[i
]);
2160 * The channel "id" is already closing, but make sure we
2161 * close all of its siblings.
2163 if (s
->x11_chanids
[i
] != id
)
2164 session_close_x11(s
->x11_chanids
[i
]);
2166 xfree(s
->x11_chanids
);
2167 s
->x11_chanids
= NULL
;
2172 if (s
->auth_proto
) {
2173 xfree(s
->auth_proto
);
2174 s
->auth_proto
= NULL
;
2177 xfree(s
->auth_data
);
2178 s
->auth_data
= NULL
;
2180 if (s
->auth_display
) {
2181 xfree(s
->auth_display
);
2182 s
->auth_display
= NULL
;
2187 session_exit_message(Session
*s
, int status
)
2191 if ((c
= channel_lookup(s
->chanid
)) == NULL
)
2192 fatal("session_exit_message: session %d: no channel %d",
2193 s
->self
, s
->chanid
);
2194 debug("session_exit_message: session %d channel %d pid %ld",
2195 s
->self
, s
->chanid
, (long)s
->pid
);
2197 if (WIFEXITED(status
)) {
2198 channel_request_start(s
->chanid
, "exit-status", 0);
2199 packet_put_int(WEXITSTATUS(status
));
2201 } else if (WIFSIGNALED(status
)) {
2202 channel_request_start(s
->chanid
, "exit-signal", 0);
2203 packet_put_cstring(sig2name(WTERMSIG(status
)));
2205 packet_put_char(WCOREDUMP(status
));
2206 #else /* WCOREDUMP */
2208 #endif /* WCOREDUMP */
2209 packet_put_cstring("");
2210 packet_put_cstring("");
2213 /* Some weird exit cause. Just exit. */
2214 packet_disconnect("wait returned status %04x.", status
);
2217 /* disconnect channel */
2218 debug("session_exit_message: release channel %d", s
->chanid
);
2221 * Adjust cleanup callback attachment to send close messages when
2222 * the channel gets EOF. The session will be then be closed
2223 * by session_close_by_channel when the childs close their fds.
2225 channel_register_cleanup(c
->self
, session_close_by_channel
, 1);
2228 * emulate a write failure with 'chan_write_failed', nobody will be
2229 * interested in data we write.
2230 * Note that we must not call 'chan_read_failed', since there could
2231 * be some more data waiting in the pipe.
2233 if (c
->ostate
!= CHAN_OUTPUT_CLOSED
)
2234 chan_write_failed(c
);
2238 session_close(Session
*s
)
2242 debug("session_close: session %d pid %ld", s
->self
, (long)s
->pid
);
2244 session_pty_cleanup(s
);
2250 xfree(s
->x11_chanids
);
2251 if (s
->auth_display
)
2252 xfree(s
->auth_display
);
2254 xfree(s
->auth_data
);
2256 xfree(s
->auth_proto
);
2258 for (i
= 0; i
< s
->num_env
; i
++) {
2259 xfree(s
->env
[i
].name
);
2260 xfree(s
->env
[i
].val
);
2264 session_proctitle(s
);
2268 session_close_by_pid(pid_t pid
, int status
)
2270 Session
*s
= session_by_pid(pid
);
2272 debug("session_close_by_pid: no session for pid %ld",
2276 if (s
->chanid
!= -1)
2277 session_exit_message(s
, status
);
2279 session_pty_cleanup(s
);
2284 * this is called when a channel dies before
2285 * the session 'child' itself dies
2288 session_close_by_channel(int id
, void *arg
)
2290 Session
*s
= session_by_channel(id
);
2294 debug("session_close_by_channel: no session for id %d", id
);
2297 debug("session_close_by_channel: channel %d child %ld",
2300 debug("session_close_by_channel: channel %d: has child", id
);
2302 * delay detach of session, but release pty, since
2303 * the fd's to the child are already closed
2306 session_pty_cleanup(s
);
2309 /* detach by removing callback */
2310 channel_cancel_cleanup(s
->chanid
);
2312 /* Close any X11 listeners associated with this session */
2313 if (s
->x11_chanids
!= NULL
) {
2314 for (i
= 0; s
->x11_chanids
[i
] != -1; i
++) {
2315 session_close_x11(s
->x11_chanids
[i
]);
2316 s
->x11_chanids
[i
] = -1;
2325 session_destroy_all(void (*closefunc
)(Session
*))
2328 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
2329 Session
*s
= &sessions
[i
];
2331 if (closefunc
!= NULL
)
2340 session_tty_list(void)
2342 static char buf
[1024];
2347 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
2348 Session
*s
= &sessions
[i
];
2349 if (s
->used
&& s
->ttyfd
!= -1) {
2351 if (strncmp(s
->tty
, "/dev/", 5) != 0) {
2352 cp
= strrchr(s
->tty
, '/');
2353 cp
= (cp
== NULL
) ? s
->tty
: cp
+ 1;
2358 strlcat(buf
, ",", sizeof buf
);
2359 strlcat(buf
, cp
, sizeof buf
);
2363 strlcpy(buf
, "notty", sizeof buf
);
2368 session_proctitle(Session
*s
)
2371 error("no user for session %d", s
->self
);
2373 setproctitle("%s@%s", s
->pw
->pw_name
, session_tty_list());
2377 session_setup_x11fwd(Session
*s
)
2380 char display
[512], auth_display
[512];
2381 char hostname
[MAXHOSTNAMELEN
];
2384 if (no_x11_forwarding_flag
) {
2385 packet_send_debug("X11 forwarding disabled in user configuration file.");
2388 if (!options
.x11_forwarding
) {
2389 debug("X11 forwarding disabled in server configuration file.");
2392 if (!options
.xauth_location
||
2393 (stat(options
.xauth_location
, &st
) == -1)) {
2394 packet_send_debug("No xauth program; cannot forward with spoofing.");
2397 if (options
.use_login
) {
2398 packet_send_debug("X11 forwarding disabled; "
2399 "not compatible with UseLogin=yes.");
2402 if (s
->display
!= NULL
) {
2403 debug("X11 display already set.");
2406 if (x11_create_display_inet(options
.x11_display_offset
,
2407 options
.x11_use_localhost
, s
->single_connection
,
2408 &s
->display_number
, &s
->x11_chanids
) == -1) {
2409 debug("x11_create_display_inet failed.");
2412 for (i
= 0; s
->x11_chanids
[i
] != -1; i
++) {
2413 channel_register_cleanup(s
->x11_chanids
[i
],
2414 session_close_single_x11
, 0);
2417 /* Set up a suitable value for the DISPLAY variable. */
2418 if (gethostname(hostname
, sizeof(hostname
)) < 0)
2419 fatal("gethostname: %.100s", strerror(errno
));
2421 * auth_display must be used as the displayname when the
2422 * authorization entry is added with xauth(1). This will be
2423 * different than the DISPLAY string for localhost displays.
2425 if (options
.x11_use_localhost
) {
2426 snprintf(display
, sizeof display
, "localhost:%u.%u",
2427 s
->display_number
, s
->screen
);
2428 snprintf(auth_display
, sizeof auth_display
, "unix:%u.%u",
2429 s
->display_number
, s
->screen
);
2430 s
->display
= xstrdup(display
);
2431 s
->auth_display
= xstrdup(auth_display
);
2433 #ifdef IPADDR_IN_DISPLAY
2435 struct in_addr my_addr
;
2437 he
= gethostbyname(hostname
);
2439 error("Can't get IP address for X11 DISPLAY.");
2440 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2443 memcpy(&my_addr
, he
->h_addr_list
[0], sizeof(struct in_addr
));
2444 snprintf(display
, sizeof display
, "%.50s:%u.%u", inet_ntoa(my_addr
),
2445 s
->display_number
, s
->screen
);
2447 snprintf(display
, sizeof display
, "%.400s:%u.%u", hostname
,
2448 s
->display_number
, s
->screen
);
2450 s
->display
= xstrdup(display
);
2451 s
->auth_display
= xstrdup(display
);
2458 do_authenticated2(Authctxt
*authctxt
)
2460 server_loop2(authctxt
);
2464 do_cleanup(Authctxt
*authctxt
)
2466 static int called
= 0;
2468 debug("do_cleanup");
2470 /* no cleanup if we're in the child for login shell */
2474 /* avoid double cleanup */
2479 if (authctxt
== NULL
)
2482 if (options
.kerberos_ticket_cleanup
&&
2484 krb5_cleanup_proc(authctxt
);
2488 if (compat20
&& options
.gss_cleanup_creds
)
2489 ssh_gssapi_cleanup_creds();
2493 if (options
.use_pam
) {
2495 sshpam_thread_cleanup();
2499 /* remove agent socket */
2500 auth_sock_cleanup_proc(authctxt
->pw
);
2503 * Cleanup ptys/utmp only if privsep is disabled,
2504 * or if running in monitor.
2506 if (!use_privsep
|| mm_is_monitor())
2507 session_destroy_all(session_pty_cleanup2
);