1 /* $OpenBSD: session.c,v 1.227 2008/02/10 10:54:29 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)
97 /* Magic name for internal sftp-server */
98 #define INTERNAL_SFTP_NAME "internal-sftp"
102 Session
*session_new(void);
103 void session_set_fds(Session
*, int, int, int);
104 void session_pty_cleanup(Session
*);
105 void session_proctitle(Session
*);
106 int session_setup_x11fwd(Session
*);
107 void do_exec_pty(Session
*, const char *);
108 void do_exec_no_pty(Session
*, const char *);
109 void do_exec(Session
*, const char *);
110 void do_login(Session
*, const char *);
111 #ifdef LOGIN_NEEDS_UTMPX
112 static void do_pre_login(Session
*s
);
114 void do_child(Session
*, const char *);
116 int check_quietlogin(Session
*, const char *);
118 static void do_authenticated1(Authctxt
*);
119 static void do_authenticated2(Authctxt
*);
121 static int session_pty_req(Session
*);
124 extern ServerOptions options
;
125 extern char *__progname
;
126 extern int log_stderr
;
127 extern int debug_flag
;
128 extern u_int utmp_len
;
129 extern int startup_pipe
;
130 extern void destroy_sensitive_data(void);
131 extern Buffer loginmsg
;
133 /* original command from peer. */
134 const char *original_command
= NULL
;
137 #define MAX_SESSIONS 20
138 Session sessions
[MAX_SESSIONS
];
140 #define SUBSYSTEM_NONE 0
141 #define SUBSYSTEM_EXT 1
142 #define SUBSYSTEM_INT_SFTP 2
144 #ifdef HAVE_LOGIN_CAP
148 static int is_child
= 0;
150 /* Name and directory of socket for authentication agent forwarding. */
151 static char *auth_sock_name
= NULL
;
152 static char *auth_sock_dir
= NULL
;
154 /* removes the agent forwarding socket */
157 auth_sock_cleanup_proc(struct passwd
*pw
)
159 if (auth_sock_name
!= NULL
) {
160 temporarily_use_uid(pw
);
161 unlink(auth_sock_name
);
162 rmdir(auth_sock_dir
);
163 auth_sock_name
= NULL
;
169 auth_input_request_forwarding(struct passwd
* pw
)
173 struct sockaddr_un sunaddr
;
175 if (auth_sock_name
!= NULL
) {
176 error("authentication forwarding requested twice.");
180 /* Temporarily drop privileged uid for mkdir/bind. */
181 temporarily_use_uid(pw
);
183 /* Allocate a buffer for the socket name, and format the name. */
184 auth_sock_name
= xmalloc(MAXPATHLEN
);
185 auth_sock_dir
= xmalloc(MAXPATHLEN
);
186 strlcpy(auth_sock_dir
, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN
);
188 /* Create private directory for socket */
189 if (mkdtemp(auth_sock_dir
) == NULL
) {
190 packet_send_debug("Agent forwarding disabled: "
191 "mkdtemp() failed: %.100s", strerror(errno
));
193 xfree(auth_sock_name
);
194 xfree(auth_sock_dir
);
195 auth_sock_name
= NULL
;
196 auth_sock_dir
= NULL
;
199 snprintf(auth_sock_name
, MAXPATHLEN
, "%s/agent.%ld",
200 auth_sock_dir
, (long) getpid());
202 /* Create the socket. */
203 sock
= socket(AF_UNIX
, SOCK_STREAM
, 0);
205 packet_disconnect("socket: %.100s", strerror(errno
));
207 /* Bind it to the name. */
208 memset(&sunaddr
, 0, sizeof(sunaddr
));
209 sunaddr
.sun_family
= AF_UNIX
;
210 strlcpy(sunaddr
.sun_path
, auth_sock_name
, sizeof(sunaddr
.sun_path
));
212 if (bind(sock
, (struct sockaddr
*)&sunaddr
, sizeof(sunaddr
)) < 0)
213 packet_disconnect("bind: %.100s", strerror(errno
));
215 /* Restore the privileged uid. */
218 /* Start listening on the socket. */
219 if (listen(sock
, SSH_LISTEN_BACKLOG
) < 0)
220 packet_disconnect("listen: %.100s", strerror(errno
));
222 /* Allocate a channel for the authentication agent socket. */
223 nc
= channel_new("auth socket",
224 SSH_CHANNEL_AUTH_SOCKET
, sock
, sock
, -1,
225 CHAN_X11_WINDOW_DEFAULT
, CHAN_X11_PACKET_DEFAULT
,
226 0, "auth socket", 1);
227 strlcpy(nc
->path
, auth_sock_name
, sizeof(nc
->path
));
232 display_loginmsg(void)
234 if (buffer_len(&loginmsg
) > 0) {
235 buffer_append(&loginmsg
, "\0", 1);
236 printf("%s", (char *)buffer_ptr(&loginmsg
));
237 buffer_clear(&loginmsg
);
242 do_authenticated(Authctxt
*authctxt
)
244 setproctitle("%s", authctxt
->pw
->pw_name
);
246 /* setup the channel layer */
247 if (!no_port_forwarding_flag
&& options
.allow_tcp_forwarding
)
248 channel_permit_all_opens();
251 do_authenticated2(authctxt
);
253 do_authenticated1(authctxt
);
255 do_cleanup(authctxt
);
259 * Prepares for an interactive session. This is called after the user has
260 * been successfully authenticated. During this message exchange, pseudo
261 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
262 * are requested, etc.
265 do_authenticated1(Authctxt
*authctxt
)
269 int success
, type
, screen_flag
;
270 int enable_compression_after_reply
= 0;
271 u_int proto_len
, data_len
, dlen
, compression_level
= 0;
275 error("no more sessions");
278 s
->authctxt
= authctxt
;
279 s
->pw
= authctxt
->pw
;
282 * We stay in this loop until the client requests to execute a shell
288 /* Get a packet from the client. */
289 type
= packet_read();
291 /* Process the packet. */
293 case SSH_CMSG_REQUEST_COMPRESSION
:
294 compression_level
= packet_get_int();
296 if (compression_level
< 1 || compression_level
> 9) {
297 packet_send_debug("Received invalid compression level %d.",
301 if (options
.compression
== COMP_NONE
) {
302 debug2("compression disabled");
305 /* Enable compression after we have responded with SUCCESS. */
306 enable_compression_after_reply
= 1;
310 case SSH_CMSG_REQUEST_PTY
:
311 success
= session_pty_req(s
);
314 case SSH_CMSG_X11_REQUEST_FORWARDING
:
315 s
->auth_proto
= packet_get_string(&proto_len
);
316 s
->auth_data
= packet_get_string(&data_len
);
318 screen_flag
= packet_get_protocol_flags() &
319 SSH_PROTOFLAG_SCREEN_NUMBER
;
320 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag
);
322 if (packet_remaining() == 4) {
324 debug2("Buggy client: "
325 "X11 screen flag missing");
326 s
->screen
= packet_get_int();
331 success
= session_setup_x11fwd(s
);
333 xfree(s
->auth_proto
);
335 s
->auth_proto
= NULL
;
340 case SSH_CMSG_AGENT_REQUEST_FORWARDING
:
341 if (no_agent_forwarding_flag
|| compat13
) {
342 debug("Authentication agent forwarding not permitted for this authentication.");
345 debug("Received authentication agent forwarding request.");
346 success
= auth_input_request_forwarding(s
->pw
);
349 case SSH_CMSG_PORT_FORWARD_REQUEST
:
350 if (no_port_forwarding_flag
) {
351 debug("Port forwarding not permitted for this authentication.");
354 if (!options
.allow_tcp_forwarding
) {
355 debug("Port forwarding not permitted.");
358 debug("Received TCP/IP port forwarding request.");
359 if (channel_input_port_forward_request(s
->pw
->pw_uid
== 0,
360 options
.gateway_ports
) < 0) {
361 debug("Port forwarding failed.");
367 case SSH_CMSG_MAX_PACKET_SIZE
:
368 if (packet_set_maxsize(packet_get_int()) > 0)
372 case SSH_CMSG_EXEC_SHELL
:
373 case SSH_CMSG_EXEC_CMD
:
374 if (type
== SSH_CMSG_EXEC_CMD
) {
375 command
= packet_get_string(&dlen
);
376 debug("Exec command '%.500s'", command
);
388 * Any unknown messages in this phase are ignored,
389 * and a failure message is returned.
391 logit("Unknown packet type received after authentication: %d", type
);
393 packet_start(success
? SSH_SMSG_SUCCESS
: SSH_SMSG_FAILURE
);
397 /* Enable compression now that we have replied if appropriate. */
398 if (enable_compression_after_reply
) {
399 enable_compression_after_reply
= 0;
400 packet_start_compression(compression_level
);
406 * This is called to fork and execute a command when we have no tty. This
407 * will call do_child from the child, and server_loop from the parent after
408 * setting up file descriptors and such.
411 do_exec_no_pty(Session
*s
, const char *command
)
416 int pin
[2], pout
[2], perr
[2];
417 /* Allocate pipes for communicating with the program. */
418 if (pipe(pin
) < 0 || pipe(pout
) < 0 || pipe(perr
) < 0)
419 packet_disconnect("Could not create pipes: %.100s",
421 #else /* USE_PIPES */
422 int inout
[2], err
[2];
423 /* Uses socket pairs to communicate with the program. */
424 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, inout
) < 0 ||
425 socketpair(AF_UNIX
, SOCK_STREAM
, 0, err
) < 0)
426 packet_disconnect("Could not create socket pairs: %.100s",
428 #endif /* USE_PIPES */
430 fatal("do_exec_no_pty: no session");
432 session_proctitle(s
);
435 if (options
.use_pam
&& !use_privsep
)
439 /* Fork the child. */
440 if ((pid
= fork()) == 0) {
443 /* Child. Reinitialize the log since the pid has changed. */
444 log_init(__progname
, options
.log_level
, options
.log_facility
, log_stderr
);
447 * Create a new session and process group since the 4.4BSD
448 * setlogin() affects the entire process group.
451 error("setsid failed: %.100s", strerror(errno
));
455 * Redirect stdin. We close the parent side of the socket
456 * pair, and make the child side the standard input.
459 if (dup2(pin
[0], 0) < 0)
460 perror("dup2 stdin");
463 /* Redirect stdout. */
465 if (dup2(pout
[1], 1) < 0)
466 perror("dup2 stdout");
469 /* Redirect stderr. */
471 if (dup2(perr
[1], 2) < 0)
472 perror("dup2 stderr");
474 #else /* USE_PIPES */
476 * Redirect stdin, stdout, and stderr. Stdin and stdout will
477 * use the same socket, as some programs (particularly rdist)
478 * seem to depend on it.
482 if (dup2(inout
[0], 0) < 0) /* stdin */
483 perror("dup2 stdin");
484 if (dup2(inout
[0], 1) < 0) /* stdout. Note: same socket as stdin. */
485 perror("dup2 stdout");
486 if (dup2(err
[0], 2) < 0) /* stderr */
487 perror("dup2 stderr");
488 #endif /* USE_PIPES */
491 cray_init_job(s
->pw
); /* set up cray jid and tmpdir */
494 /* Do processing for the child (exec command etc). */
495 do_child(s
, command
);
499 signal(WJSIGNAL
, cray_job_termination_handler
);
503 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE
);
506 packet_disconnect("fork failed: %.100s", strerror(errno
));
508 /* Set interactive/non-interactive mode. */
509 packet_set_interactive(s
->display
!= NULL
);
511 /* We are the parent. Close the child sides of the pipes. */
517 if (s
->is_subsystem
) {
521 session_set_fds(s
, pin
[1], pout
[0], perr
[0]);
523 /* Enter the interactive session. */
524 server_loop(pid
, pin
[1], pout
[0], perr
[0]);
525 /* server_loop has closed pin[1], pout[0], and perr[0]. */
527 #else /* USE_PIPES */
528 /* We are the parent. Close the child sides of the socket pairs. */
533 * Clear loginmsg, since it's the child's responsibility to display
534 * it to the user, otherwise multiple sessions may accumulate
535 * multiple copies of the login messages.
537 buffer_clear(&loginmsg
);
540 * Enter the interactive session. Note: server_loop must be able to
541 * handle the case that fdin and fdout are the same.
544 session_set_fds(s
, inout
[1], inout
[1], s
->is_subsystem
? -1 : err
[1]);
546 server_loop(pid
, inout
[1], inout
[1], err
[1]);
547 /* server_loop has closed inout[1] and err[1]. */
549 #endif /* USE_PIPES */
553 * This is called to fork and execute a command when we have a tty. This
554 * will call do_child from the child, and server_loop from the parent after
555 * setting up file descriptors, controlling tty, updating wtmp, utmp,
556 * lastlog, and other such operations.
559 do_exec_pty(Session
*s
, const char *command
)
561 int fdout
, ptyfd
, ttyfd
, ptymaster
;
565 fatal("do_exec_pty: no session");
570 if (options
.use_pam
) {
571 do_pam_set_tty(s
->tty
);
577 /* Fork the child. */
578 if ((pid
= fork()) == 0) {
581 /* Child. Reinitialize the log because the pid has changed. */
582 log_init(__progname
, options
.log_level
, options
.log_facility
, log_stderr
);
583 /* Close the master side of the pseudo tty. */
586 /* Make the pseudo tty our controlling tty. */
587 pty_make_controlling_tty(&ttyfd
, s
->tty
);
589 /* Redirect stdin/stdout/stderr from the pseudo tty. */
590 if (dup2(ttyfd
, 0) < 0)
591 error("dup2 stdin: %s", strerror(errno
));
592 if (dup2(ttyfd
, 1) < 0)
593 error("dup2 stdout: %s", strerror(errno
));
594 if (dup2(ttyfd
, 2) < 0)
595 error("dup2 stderr: %s", strerror(errno
));
597 /* Close the extra descriptor for the pseudo tty. */
600 /* record login, etc. similar to login(1) */
602 if (!(options
.use_login
&& command
== NULL
)) {
604 cray_init_job(s
->pw
); /* set up cray jid and tmpdir */
606 do_login(s
, command
);
608 # ifdef LOGIN_NEEDS_UTMPX
614 /* Do common processing for the child, such as execing the command. */
615 do_child(s
, command
);
619 signal(WJSIGNAL
, cray_job_termination_handler
);
623 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE
);
626 packet_disconnect("fork failed: %.100s", strerror(errno
));
629 /* Parent. Close the slave side of the pseudo tty. */
633 * Create another descriptor of the pty master side for use as the
634 * standard input. We could use the original descriptor, but this
635 * simplifies code in server_loop. The descriptor is bidirectional.
639 packet_disconnect("dup #1 failed: %.100s", strerror(errno
));
641 /* we keep a reference to the pty master */
642 ptymaster
= dup(ptyfd
);
644 packet_disconnect("dup #2 failed: %.100s", strerror(errno
));
645 s
->ptymaster
= ptymaster
;
647 /* Enter interactive session. */
648 packet_set_interactive(1);
650 session_set_fds(s
, ptyfd
, fdout
, -1);
652 server_loop(pid
, ptyfd
, fdout
, -1);
653 /* server_loop _has_ closed ptyfd and fdout. */
657 #ifdef LOGIN_NEEDS_UTMPX
659 do_pre_login(Session
*s
)
662 struct sockaddr_storage from
;
663 pid_t pid
= getpid();
666 * Get IP address of client. If the connection is not a socket, let
667 * the address be 0.0.0.0.
669 memset(&from
, 0, sizeof(from
));
670 fromlen
= sizeof(from
);
671 if (packet_connection_is_on_socket()) {
672 if (getpeername(packet_get_connection_in(),
673 (struct sockaddr
*)&from
, &fromlen
) < 0) {
674 debug("getpeername: %.100s", strerror(errno
));
679 record_utmp_only(pid
, s
->tty
, s
->pw
->pw_name
,
680 get_remote_name_or_ip(utmp_len
, options
.use_dns
),
681 (struct sockaddr
*)&from
, fromlen
);
686 * This is called to fork and execute a command. If another command is
687 * to be forced, execute that instead.
690 do_exec(Session
*s
, const char *command
)
692 if (options
.adm_forced_command
) {
693 original_command
= command
;
694 command
= options
.adm_forced_command
;
695 if (strcmp(INTERNAL_SFTP_NAME
, command
) == 0)
696 s
->is_subsystem
= SUBSYSTEM_INT_SFTP
;
697 else if (s
->is_subsystem
)
698 s
->is_subsystem
= SUBSYSTEM_EXT
;
699 debug("Forced command (config) '%.900s'", command
);
700 } else if (forced_command
) {
701 original_command
= command
;
702 command
= forced_command
;
703 if (strcmp(INTERNAL_SFTP_NAME
, command
) == 0)
704 s
->is_subsystem
= SUBSYSTEM_INT_SFTP
;
705 else if (s
->is_subsystem
)
706 s
->is_subsystem
= SUBSYSTEM_EXT
;
707 debug("Forced command (key option) '%.900s'", command
);
710 #ifdef SSH_AUDIT_EVENTS
712 PRIVSEP(audit_run_command(command
));
713 else if (s
->ttyfd
== -1) {
714 char *shell
= s
->pw
->pw_shell
;
716 if (shell
[0] == '\0') /* empty shell means /bin/sh */
718 PRIVSEP(audit_run_command(shell
));
722 do_exec_pty(s
, command
);
724 do_exec_no_pty(s
, command
);
726 original_command
= NULL
;
729 * Clear loginmsg: it's the child's responsibility to display
730 * it to the user, otherwise multiple sessions may accumulate
731 * multiple copies of the login messages.
733 buffer_clear(&loginmsg
);
736 /* administrative, login(1)-like work */
738 do_login(Session
*s
, const char *command
)
741 struct sockaddr_storage from
;
742 struct passwd
* pw
= s
->pw
;
743 pid_t pid
= getpid();
746 * Get IP address of client. If the connection is not a socket, let
747 * the address be 0.0.0.0.
749 memset(&from
, 0, sizeof(from
));
750 fromlen
= sizeof(from
);
751 if (packet_connection_is_on_socket()) {
752 if (getpeername(packet_get_connection_in(),
753 (struct sockaddr
*) & from
, &fromlen
) < 0) {
754 debug("getpeername: %.100s", strerror(errno
));
759 /* Record that there was a login on that tty from the remote host. */
761 record_login(pid
, s
->tty
, pw
->pw_name
, pw
->pw_uid
,
762 get_remote_name_or_ip(utmp_len
,
764 (struct sockaddr
*)&from
, fromlen
);
768 * If password change is needed, do it now.
769 * This needs to occur before the ~/.hushlogin check.
771 if (options
.use_pam
&& !use_privsep
&& s
->authctxt
->force_pwchange
) {
774 s
->authctxt
->force_pwchange
= 0;
775 /* XXX - signal [net] parent to enable forwardings */
779 if (check_quietlogin(s
, command
))
788 * Display the message of the day.
796 if (options
.print_motd
) {
797 #ifdef HAVE_LOGIN_CAP
798 f
= fopen(login_getcapstr(lc
, "welcome", "/etc/motd",
801 f
= fopen("/etc/motd", "r");
804 while (fgets(buf
, sizeof(buf
), f
))
813 * Check for quiet login, either .hushlogin or command given.
816 check_quietlogin(Session
*s
, const char *command
)
819 struct passwd
*pw
= s
->pw
;
822 /* Return 1 if .hushlogin exists or a command given. */
825 snprintf(buf
, sizeof(buf
), "%.200s/.hushlogin", pw
->pw_dir
);
826 #ifdef HAVE_LOGIN_CAP
827 if (login_getcapbool(lc
, "hushlogin", 0) || stat(buf
, &st
) >= 0)
830 if (stat(buf
, &st
) >= 0)
837 * Sets the value of the given variable in the environment. If the variable
838 * already exists, its value is overriden.
841 child_set_env(char ***envp
, u_int
*envsizep
, const char *name
,
849 * If we're passed an uninitialized list, allocate a single null
850 * entry before continuing.
852 if (*envp
== NULL
&& *envsizep
== 0) {
853 *envp
= xmalloc(sizeof(char *));
859 * Find the slot where the value should be stored. If the variable
860 * already exists, we reuse the slot; otherwise we append a new slot
861 * at the end of the array, expanding if necessary.
864 namelen
= strlen(name
);
865 for (i
= 0; env
[i
]; i
++)
866 if (strncmp(env
[i
], name
, namelen
) == 0 && env
[i
][namelen
] == '=')
869 /* Reuse the slot. */
872 /* New variable. Expand if necessary. */
874 if (i
>= envsize
- 1) {
876 fatal("child_set_env: too many env vars");
878 env
= (*envp
) = xrealloc(env
, envsize
, sizeof(char *));
881 /* Need to set the NULL pointer at end of array beyond the new slot. */
885 /* Allocate space and format the variable in the appropriate slot. */
886 env
[i
] = xmalloc(strlen(name
) + 1 + strlen(value
) + 1);
887 snprintf(env
[i
], strlen(name
) + 1 + strlen(value
) + 1, "%s=%s", name
, value
);
891 * Reads environment variables from the given file and adds/overrides them
892 * into the environment. If the file does not exist, this does nothing.
893 * Otherwise, it must consist of empty lines, comments (line starts with '#')
894 * and assignments of the form name=value. No other forms are allowed.
897 read_environment_file(char ***env
, u_int
*envsize
,
898 const char *filename
)
905 f
= fopen(filename
, "r");
909 while (fgets(buf
, sizeof(buf
), f
)) {
911 fatal("Too many lines in environment file %s", filename
);
912 for (cp
= buf
; *cp
== ' ' || *cp
== '\t'; cp
++)
914 if (!*cp
|| *cp
== '#' || *cp
== '\n')
917 cp
[strcspn(cp
, "\n")] = '\0';
919 value
= strchr(cp
, '=');
921 fprintf(stderr
, "Bad line %u in %.100s\n", lineno
,
926 * Replace the equals sign by nul, and advance value to
931 child_set_env(env
, envsize
, cp
, value
);
936 #ifdef HAVE_ETC_DEFAULT_LOGIN
938 * Return named variable from specified environment, or NULL if not present.
941 child_get_env(char **env
, const char *name
)
947 for (i
=0; env
[i
] != NULL
; i
++)
948 if (strncmp(name
, env
[i
], len
) == 0 && env
[i
][len
] == '=')
949 return(env
[i
] + len
+ 1);
954 * Read /etc/default/login.
955 * We pick up the PATH (or SUPATH for root) and UMASK.
958 read_etc_default_login(char ***env
, u_int
*envsize
, uid_t uid
)
960 char **tmpenv
= NULL
, *var
;
961 u_int i
, tmpenvsize
= 0;
965 * We don't want to copy the whole file to the child's environment,
966 * so we use a temporary environment and copy the variables we're
969 read_environment_file(&tmpenv
, &tmpenvsize
, "/etc/default/login");
975 var
= child_get_env(tmpenv
, "SUPATH");
977 var
= child_get_env(tmpenv
, "PATH");
979 child_set_env(env
, envsize
, "PATH", var
);
981 if ((var
= child_get_env(tmpenv
, "UMASK")) != NULL
)
982 if (sscanf(var
, "%5lo", &mask
) == 1)
985 for (i
= 0; tmpenv
[i
] != NULL
; i
++)
989 #endif /* HAVE_ETC_DEFAULT_LOGIN */
992 copy_environment(char **source
, char ***env
, u_int
*envsize
)
994 char *var_name
, *var_val
;
1000 for(i
= 0; source
[i
] != NULL
; i
++) {
1001 var_name
= xstrdup(source
[i
]);
1002 if ((var_val
= strstr(var_name
, "=")) == NULL
) {
1008 debug3("Copy environment: %s=%s", var_name
, var_val
);
1009 child_set_env(env
, envsize
, var_name
, var_val
);
1016 do_setup_env(Session
*s
, const char *shell
)
1021 struct passwd
*pw
= s
->pw
;
1022 #ifndef HAVE_LOGIN_CAP
1026 /* Initialize the environment. */
1028 env
= xcalloc(envsize
, sizeof(char *));
1033 * The Windows environment contains some setting which are
1034 * important for a running system. They must not be dropped.
1039 p
= fetch_windows_environment();
1040 copy_environment(p
, &env
, &envsize
);
1041 free_windows_environment(p
);
1046 /* Allow any GSSAPI methods that we've used to alter
1047 * the childs environment as they see fit
1049 ssh_gssapi_do_child(&env
, &envsize
);
1052 if (!options
.use_login
) {
1053 /* Set basic environment. */
1054 for (i
= 0; i
< s
->num_env
; i
++)
1055 child_set_env(&env
, &envsize
, s
->env
[i
].name
,
1058 child_set_env(&env
, &envsize
, "USER", pw
->pw_name
);
1059 child_set_env(&env
, &envsize
, "LOGNAME", pw
->pw_name
);
1061 child_set_env(&env
, &envsize
, "LOGIN", pw
->pw_name
);
1063 child_set_env(&env
, &envsize
, "HOME", pw
->pw_dir
);
1064 #ifdef HAVE_LOGIN_CAP
1065 if (setusercontext(lc
, pw
, pw
->pw_uid
, LOGIN_SETPATH
) < 0)
1066 child_set_env(&env
, &envsize
, "PATH", _PATH_STDPATH
);
1068 child_set_env(&env
, &envsize
, "PATH", getenv("PATH"));
1069 #else /* HAVE_LOGIN_CAP */
1070 # ifndef HAVE_CYGWIN
1072 * There's no standard path on Windows. The path contains
1073 * important components pointing to the system directories,
1074 * needed for loading shared libraries. So the path better
1075 * remains intact here.
1077 # ifdef HAVE_ETC_DEFAULT_LOGIN
1078 read_etc_default_login(&env
, &envsize
, pw
->pw_uid
);
1079 path
= child_get_env(env
, "PATH");
1080 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1081 if (path
== NULL
|| *path
== '\0') {
1082 child_set_env(&env
, &envsize
, "PATH",
1083 s
->pw
->pw_uid
== 0 ?
1084 SUPERUSER_PATH
: _PATH_STDPATH
);
1086 # endif /* HAVE_CYGWIN */
1087 #endif /* HAVE_LOGIN_CAP */
1089 snprintf(buf
, sizeof buf
, "%.200s/%.50s",
1090 _PATH_MAILDIR
, pw
->pw_name
);
1091 child_set_env(&env
, &envsize
, "MAIL", buf
);
1093 /* Normal systems set SHELL by default. */
1094 child_set_env(&env
, &envsize
, "SHELL", shell
);
1097 child_set_env(&env
, &envsize
, "TZ", getenv("TZ"));
1099 /* Set custom environment options from RSA authentication. */
1100 if (!options
.use_login
) {
1101 while (custom_environment
) {
1102 struct envstring
*ce
= custom_environment
;
1105 for (i
= 0; str
[i
] != '=' && str
[i
]; i
++)
1107 if (str
[i
] == '=') {
1109 child_set_env(&env
, &envsize
, str
, str
+ i
+ 1);
1111 custom_environment
= ce
->next
;
1117 /* SSH_CLIENT deprecated */
1118 snprintf(buf
, sizeof buf
, "%.50s %d %d",
1119 get_remote_ipaddr(), get_remote_port(), get_local_port());
1120 child_set_env(&env
, &envsize
, "SSH_CLIENT", buf
);
1122 laddr
= get_local_ipaddr(packet_get_connection_in());
1123 snprintf(buf
, sizeof buf
, "%.50s %d %.50s %d",
1124 get_remote_ipaddr(), get_remote_port(), laddr
, get_local_port());
1126 child_set_env(&env
, &envsize
, "SSH_CONNECTION", buf
);
1129 child_set_env(&env
, &envsize
, "SSH_TTY", s
->tty
);
1131 child_set_env(&env
, &envsize
, "TERM", s
->term
);
1133 child_set_env(&env
, &envsize
, "DISPLAY", s
->display
);
1134 if (original_command
)
1135 child_set_env(&env
, &envsize
, "SSH_ORIGINAL_COMMAND",
1139 if (cray_tmpdir
[0] != '\0')
1140 child_set_env(&env
, &envsize
, "TMPDIR", cray_tmpdir
);
1141 #endif /* _UNICOS */
1144 * Since we clear KRB5CCNAME at startup, if it's set now then it
1145 * must have been set by a native authentication method (eg AIX or
1146 * SIA), so copy it to the child.
1151 if ((cp
= getenv("KRB5CCNAME")) != NULL
)
1152 child_set_env(&env
, &envsize
, "KRB5CCNAME", cp
);
1159 if ((cp
= getenv("AUTHSTATE")) != NULL
)
1160 child_set_env(&env
, &envsize
, "AUTHSTATE", cp
);
1161 read_environment_file(&env
, &envsize
, "/etc/environment");
1165 if (s
->authctxt
->krb5_ccname
)
1166 child_set_env(&env
, &envsize
, "KRB5CCNAME",
1167 s
->authctxt
->krb5_ccname
);
1171 * Pull in any environment variables that may have
1174 if (options
.use_pam
) {
1177 p
= fetch_pam_child_environment();
1178 copy_environment(p
, &env
, &envsize
);
1179 free_pam_environment(p
);
1181 p
= fetch_pam_environment();
1182 copy_environment(p
, &env
, &envsize
);
1183 free_pam_environment(p
);
1185 #endif /* USE_PAM */
1187 if (auth_sock_name
!= NULL
)
1188 child_set_env(&env
, &envsize
, SSH_AUTHSOCKET_ENV_NAME
,
1191 /* read $HOME/.ssh/environment. */
1192 if (options
.permit_user_env
&& !options
.use_login
) {
1193 snprintf(buf
, sizeof buf
, "%.200s/.ssh/environment",
1194 strcmp(pw
->pw_dir
, "/") ? pw
->pw_dir
: "");
1195 read_environment_file(&env
, &envsize
, buf
);
1198 /* dump the environment */
1199 fprintf(stderr
, "Environment:\n");
1200 for (i
= 0; env
[i
]; i
++)
1201 fprintf(stderr
, " %.200s\n", env
[i
]);
1207 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1208 * first in this order).
1211 do_rc_files(Session
*s
, const char *shell
)
1219 s
->display
!= NULL
&& s
->auth_proto
!= NULL
&& s
->auth_data
!= NULL
;
1221 /* ignore _PATH_SSH_USER_RC for subsystems */
1222 if (!s
->is_subsystem
&& (stat(_PATH_SSH_USER_RC
, &st
) >= 0)) {
1223 snprintf(cmd
, sizeof cmd
, "%s -c '%s %s'",
1224 shell
, _PATH_BSHELL
, _PATH_SSH_USER_RC
);
1226 fprintf(stderr
, "Running %s\n", cmd
);
1227 f
= popen(cmd
, "w");
1230 fprintf(f
, "%s %s\n", s
->auth_proto
,
1234 fprintf(stderr
, "Could not run %s\n",
1236 } else if (stat(_PATH_SSH_SYSTEM_RC
, &st
) >= 0) {
1238 fprintf(stderr
, "Running %s %s\n", _PATH_BSHELL
,
1239 _PATH_SSH_SYSTEM_RC
);
1240 f
= popen(_PATH_BSHELL
" " _PATH_SSH_SYSTEM_RC
, "w");
1243 fprintf(f
, "%s %s\n", s
->auth_proto
,
1247 fprintf(stderr
, "Could not run %s\n",
1248 _PATH_SSH_SYSTEM_RC
);
1249 } else if (do_xauth
&& options
.xauth_location
!= NULL
) {
1250 /* Add authority data to .Xauthority if appropriate. */
1253 "Running %.500s remove %.100s\n",
1254 options
.xauth_location
, s
->auth_display
);
1256 "%.500s add %.100s %.100s %.100s\n",
1257 options
.xauth_location
, s
->auth_display
,
1258 s
->auth_proto
, s
->auth_data
);
1260 snprintf(cmd
, sizeof cmd
, "%s -q -",
1261 options
.xauth_location
);
1262 f
= popen(cmd
, "w");
1264 fprintf(f
, "remove %s\n",
1266 fprintf(f
, "add %s %s %s\n",
1267 s
->auth_display
, s
->auth_proto
,
1271 fprintf(stderr
, "Could not run %s\n",
1278 do_nologin(struct passwd
*pw
)
1283 #ifdef HAVE_LOGIN_CAP
1284 if (!login_getcapbool(lc
, "ignorenologin", 0) && pw
->pw_uid
)
1285 f
= fopen(login_getcapstr(lc
, "nologin", _PATH_NOLOGIN
,
1286 _PATH_NOLOGIN
), "r");
1289 f
= fopen(_PATH_NOLOGIN
, "r");
1292 /* /etc/nologin exists. Print its contents and exit. */
1293 logit("User %.100s not allowed because %s exists",
1294 pw
->pw_name
, _PATH_NOLOGIN
);
1295 while (fgets(buf
, sizeof(buf
), f
))
1304 * Chroot into a directory after checking it for safety: all path components
1305 * must be root-owned directories with strict permissions.
1308 safely_chroot(const char *path
, uid_t uid
)
1311 char component
[MAXPATHLEN
];
1315 fatal("chroot path does not begin at root");
1316 if (strlen(path
) >= sizeof(component
))
1317 fatal("chroot path too long");
1320 * Descend the path, checking that each component is a
1321 * root-owned directory with strict permissions.
1323 for (cp
= path
; cp
!= NULL
;) {
1324 if ((cp
= strchr(cp
, '/')) == NULL
)
1325 strlcpy(component
, path
, sizeof(component
));
1328 memcpy(component
, path
, cp
- path
);
1329 component
[cp
- path
] = '\0';
1332 debug3("%s: checking '%s'", __func__
, component
);
1334 if (stat(component
, &st
) != 0)
1335 fatal("%s: stat(\"%s\"): %s", __func__
,
1336 component
, strerror(errno
));
1337 if (st
.st_uid
!= 0 || (st
.st_mode
& 022) != 0)
1338 fatal("bad ownership or modes for chroot "
1339 "directory %s\"%s\"",
1340 cp
== NULL
? "" : "component ", component
);
1341 if (!S_ISDIR(st
.st_mode
))
1342 fatal("chroot path %s\"%s\" is not a directory",
1343 cp
== NULL
? "" : "component ", component
);
1347 if (chdir(path
) == -1)
1348 fatal("Unable to chdir to chroot path \"%s\": "
1349 "%s", path
, strerror(errno
));
1350 if (chroot(path
) == -1)
1351 fatal("chroot(\"%s\"): %s", path
, strerror(errno
));
1352 if (chdir("/") == -1)
1353 fatal("%s: chdir(/) after chroot: %s",
1354 __func__
, strerror(errno
));
1355 verbose("Changed root directory to \"%s\"", path
);
1358 /* Set login name, uid, gid, and groups. */
1360 do_setusercontext(struct passwd
*pw
)
1362 char *chroot_path
, *tmp
;
1365 if (getuid() == 0 || geteuid() == 0)
1366 #endif /* HAVE_CYGWIN */
1369 #ifdef HAVE_SETPCRED
1370 if (setpcred(pw
->pw_name
, (char **)NULL
) == -1)
1371 fatal("Failed to set process credentials");
1372 #endif /* HAVE_SETPCRED */
1373 #ifdef HAVE_LOGIN_CAP
1378 if (options
.gss_authentication
) {
1379 temporarily_use_uid(pw
);
1380 ssh_gssapi_storecreds();
1385 if (options
.use_pam
) {
1387 do_pam_setcred(use_privsep
);
1389 # endif /* USE_PAM */
1390 if (setusercontext(lc
, pw
, pw
->pw_uid
,
1391 (LOGIN_SETALL
& ~(LOGIN_SETPATH
|LOGIN_SETUSER
))) < 0) {
1392 perror("unable to set user context");
1396 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1397 /* Sets login uid for accounting */
1398 if (getluid() == -1 && setluid(pw
->pw_uid
) == -1)
1399 error("setluid: %s", strerror(errno
));
1400 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1402 if (setlogin(pw
->pw_name
) < 0)
1403 error("setlogin failed: %s", strerror(errno
));
1404 if (setgid(pw
->pw_gid
) < 0) {
1408 /* Initialize the group list. */
1409 if (initgroups(pw
->pw_name
, pw
->pw_gid
) < 0) {
1410 perror("initgroups");
1415 if (options
.gss_authentication
) {
1416 temporarily_use_uid(pw
);
1417 ssh_gssapi_storecreds();
1423 * PAM credentials may take the form of supplementary groups.
1424 * These will have been wiped by the above initgroups() call.
1425 * Reestablish them here.
1427 if (options
.use_pam
) {
1429 do_pam_setcred(use_privsep
);
1431 # endif /* USE_PAM */
1432 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1433 irix_setusercontext(pw
);
1434 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1439 if (set_id(pw
->pw_name
) != 0) {
1442 # endif /* USE_LIBIAF */
1445 if (options
.chroot_directory
!= NULL
&&
1446 strcasecmp(options
.chroot_directory
, "none") != 0) {
1447 tmp
= tilde_expand_filename(options
.chroot_directory
,
1449 chroot_path
= percent_expand(tmp
, "h", pw
->pw_dir
,
1450 "u", pw
->pw_name
, (char *)NULL
);
1451 safely_chroot(chroot_path
, pw
->pw_uid
);
1456 #ifdef HAVE_LOGIN_CAP
1457 if (setusercontext(lc
, pw
, pw
->pw_uid
, LOGIN_SETUSER
) < 0) {
1458 perror("unable to set user context (setuser)");
1462 /* Permanently switch to the desired uid. */
1463 permanently_set_uid(pw
);
1470 if (getuid() != pw
->pw_uid
|| geteuid() != pw
->pw_uid
)
1471 fatal("Failed to set uids to %u.", (u_int
) pw
->pw_uid
);
1474 ssh_selinux_setup_exec_context(pw
->pw_name
);
1479 do_pwchange(Session
*s
)
1482 fprintf(stderr
, "WARNING: Your password has expired.\n");
1483 if (s
->ttyfd
!= -1) {
1485 "You must change your password now and login again!\n");
1486 #ifdef PASSWD_NEEDS_USERNAME
1487 execl(_PATH_PASSWD_PROG
, "passwd", s
->pw
->pw_name
,
1490 execl(_PATH_PASSWD_PROG
, "passwd", (char *)NULL
);
1495 "Password change required but no TTY available.\n");
1501 launch_login(struct passwd
*pw
, const char *hostname
)
1503 /* Launch login(1). */
1505 execl(LOGIN_PROGRAM
, "login", "-h", hostname
,
1506 #ifdef xxxLOGIN_NEEDS_TERM
1507 (s
->term
? s
->term
: "unknown"),
1508 #endif /* LOGIN_NEEDS_TERM */
1509 #ifdef LOGIN_NO_ENDOPT
1510 "-p", "-f", pw
->pw_name
, (char *)NULL
);
1512 "-p", "-f", "--", pw
->pw_name
, (char *)NULL
);
1515 /* Login couldn't be executed, die. */
1522 child_close_fds(void)
1526 if (packet_get_connection_in() == packet_get_connection_out())
1527 close(packet_get_connection_in());
1529 close(packet_get_connection_in());
1530 close(packet_get_connection_out());
1533 * Close all descriptors related to channels. They will still remain
1534 * open in the parent.
1536 /* XXX better use close-on-exec? -markus */
1537 channel_close_all();
1540 * Close any extra file descriptors. Note that there may still be
1541 * descriptors left by system functions. They will be closed later.
1546 * Close any extra open file descriptors so that we don't have them
1547 * hanging around in clients. Note that we want to do this after
1548 * initgroups, because at least on Solaris 2.3 it leaves file
1551 for (i
= 3; i
< 64; i
++)
1556 * Performs common processing for the child, such as setting up the
1557 * environment, closing extra file descriptors, setting the user and group
1558 * ids, and executing the command or shell.
1562 do_child(Session
*s
, const char *command
)
1564 extern char **environ
;
1566 char *argv
[ARGV_MAX
];
1567 const char *shell
, *shell0
, *hostname
= NULL
;
1568 struct passwd
*pw
= s
->pw
;
1570 /* remove hostkey from the child's memory */
1571 destroy_sensitive_data();
1573 /* Force a password change */
1574 if (s
->authctxt
->force_pwchange
) {
1575 do_setusercontext(pw
);
1581 /* login(1) is only called if we execute the login shell */
1582 if (options
.use_login
&& command
!= NULL
)
1583 options
.use_login
= 0;
1586 cray_setup(pw
->pw_uid
, pw
->pw_name
, command
);
1587 #endif /* _UNICOS */
1590 * Login(1) does this as well, and it needs uid 0 for the "-h"
1591 * switch, so we let login(1) to this for us.
1593 if (!options
.use_login
) {
1595 session_setup_sia(pw
, s
->ttyfd
== -1 ? NULL
: s
->tty
);
1596 if (!check_quietlogin(s
, command
))
1598 #else /* HAVE_OSF_SIA */
1599 /* When PAM is enabled we rely on it to do the nologin check */
1600 if (!options
.use_pam
)
1602 do_setusercontext(pw
);
1604 * PAM session modules in do_setusercontext may have
1605 * generated messages, so if this in an interactive
1606 * login then display them too.
1608 if (!check_quietlogin(s
, command
))
1610 #endif /* HAVE_OSF_SIA */
1614 if (options
.use_pam
&& !options
.use_login
&& !is_pam_session_open()) {
1615 debug3("PAM session not opened, exiting");
1622 * Get the shell from the password data. An empty shell field is
1623 * legal, and means /bin/sh.
1625 shell
= (pw
->pw_shell
[0] == '\0') ? _PATH_BSHELL
: pw
->pw_shell
;
1628 * Make sure $SHELL points to the shell from the password file,
1629 * even if shell is overridden from login.conf
1631 env
= do_setup_env(s
, shell
);
1633 #ifdef HAVE_LOGIN_CAP
1634 shell
= login_getcapstr(lc
, "shell", (char *)shell
, (char *)shell
);
1637 /* we have to stash the hostname before we close our socket. */
1638 if (options
.use_login
)
1639 hostname
= get_remote_name_or_ip(utmp_len
,
1642 * Close the connection descriptors; note that this is the child, and
1643 * the server will still have the socket open, and it is important
1644 * that we do not shutdown it. Note that the descriptors cannot be
1645 * closed before building the environment, as we call
1646 * get_remote_ipaddr there.
1651 * Must take new environment into use so that .ssh/rc,
1652 * /etc/ssh/sshrc and xauth are run in the proper environment.
1656 #if defined(KRB5) && defined(USE_AFS)
1658 * At this point, we check to see if AFS is active and if we have
1659 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1660 * if we can (and need to) extend the ticket into an AFS token. If
1661 * we don't do this, we run into potential problems if the user's
1662 * home directory is in AFS and it's not world-readable.
1665 if (options
.kerberos_get_afs_token
&& k_hasafs() &&
1666 (s
->authctxt
->krb5_ctx
!= NULL
)) {
1669 debug("Getting AFS token");
1673 if (k_afs_cell_of_file(pw
->pw_dir
, cell
, sizeof(cell
)) == 0)
1674 krb5_afslog(s
->authctxt
->krb5_ctx
,
1675 s
->authctxt
->krb5_fwd_ccache
, cell
, NULL
);
1677 krb5_afslog_home(s
->authctxt
->krb5_ctx
,
1678 s
->authctxt
->krb5_fwd_ccache
, NULL
, NULL
, pw
->pw_dir
);
1682 /* Change current directory to the user's home directory. */
1683 if (chdir(pw
->pw_dir
) < 0) {
1684 fprintf(stderr
, "Could not chdir to home directory %s: %s\n",
1685 pw
->pw_dir
, strerror(errno
));
1686 #ifdef HAVE_LOGIN_CAP
1687 if (login_getcapbool(lc
, "requirehome", 0))
1692 if (!options
.use_login
)
1693 do_rc_files(s
, shell
);
1695 /* restore SIGPIPE for child */
1696 signal(SIGPIPE
, SIG_DFL
);
1698 if (s
->is_subsystem
== SUBSYSTEM_INT_SFTP
) {
1699 extern int optind
, optreset
;
1703 setproctitle("%s@internal-sftp-server", s
->pw
->pw_name
);
1704 args
= strdup(command
? command
: "sftp-server");
1705 for (i
= 0, (p
= strtok(args
, " ")); p
; (p
= strtok(NULL
, " ")))
1706 if (i
< ARGV_MAX
- 1)
1709 optind
= optreset
= 1;
1710 __progname
= argv
[0];
1711 exit(sftp_server_main(i
, argv
, s
->pw
));
1714 if (options
.use_login
) {
1715 launch_login(pw
, hostname
);
1719 /* Get the last component of the shell name. */
1720 if ((shell0
= strrchr(shell
, '/')) != NULL
)
1726 * If we have no command, execute the shell. In this case, the shell
1727 * name to be passed in argv[0] is preceded by '-' to indicate that
1728 * this is a login shell.
1733 /* Start the shell. Set initial character to '-'. */
1736 if (strlcpy(argv0
+ 1, shell0
, sizeof(argv0
) - 1)
1737 >= sizeof(argv0
) - 1) {
1743 /* Execute the shell. */
1746 execve(shell
, argv
, env
);
1748 /* Executing the shell failed. */
1753 * Execute the command using the user's shell. This uses the -c
1754 * option to execute the command.
1756 argv
[0] = (char *) shell0
;
1758 argv
[2] = (char *) command
;
1760 execve(shell
, argv
, env
);
1769 static int did_init
= 0;
1771 debug("session_new: init");
1772 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1773 sessions
[i
].used
= 0;
1777 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1778 Session
*s
= &sessions
[i
];
1780 memset(s
, 0, sizeof(*s
));
1786 s
->x11_chanids
= NULL
;
1787 debug("session_new: session %d", i
);
1798 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1799 Session
*s
= &sessions
[i
];
1800 debug("dump: used %d session %d %p channel %d pid %ld",
1810 session_open(Authctxt
*authctxt
, int chanid
)
1812 Session
*s
= session_new();
1813 debug("session_open: channel %d", chanid
);
1815 error("no more sessions");
1818 s
->authctxt
= authctxt
;
1819 s
->pw
= authctxt
->pw
;
1820 if (s
->pw
== NULL
|| !authctxt
->valid
)
1821 fatal("no user for session %d", s
->self
);
1822 debug("session_open: session %d: link with channel %d", s
->self
, chanid
);
1828 session_by_tty(char *tty
)
1831 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1832 Session
*s
= &sessions
[i
];
1833 if (s
->used
&& s
->ttyfd
!= -1 && strcmp(s
->tty
, tty
) == 0) {
1834 debug("session_by_tty: session %d tty %s", i
, tty
);
1838 debug("session_by_tty: unknown tty %.100s", tty
);
1844 session_by_channel(int id
)
1847 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1848 Session
*s
= &sessions
[i
];
1849 if (s
->used
&& s
->chanid
== id
) {
1850 debug("session_by_channel: session %d channel %d", i
, id
);
1854 debug("session_by_channel: unknown channel %d", id
);
1860 session_by_x11_channel(int id
)
1864 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1865 Session
*s
= &sessions
[i
];
1867 if (s
->x11_chanids
== NULL
|| !s
->used
)
1869 for (j
= 0; s
->x11_chanids
[j
] != -1; j
++) {
1870 if (s
->x11_chanids
[j
] == id
) {
1871 debug("session_by_x11_channel: session %d "
1872 "channel %d", s
->self
, id
);
1877 debug("session_by_x11_channel: unknown channel %d", id
);
1883 session_by_pid(pid_t pid
)
1886 debug("session_by_pid: pid %ld", (long)pid
);
1887 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1888 Session
*s
= &sessions
[i
];
1889 if (s
->used
&& s
->pid
== pid
)
1892 error("session_by_pid: unknown pid %ld", (long)pid
);
1898 session_window_change_req(Session
*s
)
1900 s
->col
= packet_get_int();
1901 s
->row
= packet_get_int();
1902 s
->xpixel
= packet_get_int();
1903 s
->ypixel
= packet_get_int();
1905 pty_change_window_size(s
->ptyfd
, s
->row
, s
->col
, s
->xpixel
, s
->ypixel
);
1910 session_pty_req(Session
*s
)
1916 debug("Allocating a pty not permitted for this authentication.");
1919 if (s
->ttyfd
!= -1) {
1920 packet_disconnect("Protocol error: you already have a pty.");
1924 s
->term
= packet_get_string(&len
);
1927 s
->col
= packet_get_int();
1928 s
->row
= packet_get_int();
1930 s
->row
= packet_get_int();
1931 s
->col
= packet_get_int();
1933 s
->xpixel
= packet_get_int();
1934 s
->ypixel
= packet_get_int();
1936 if (strcmp(s
->term
, "") == 0) {
1941 /* Allocate a pty and open it. */
1942 debug("Allocating pty.");
1943 if (!PRIVSEP(pty_allocate(&s
->ptyfd
, &s
->ttyfd
, s
->tty
, sizeof(s
->tty
)))) {
1949 error("session_pty_req: session %d alloc failed", s
->self
);
1952 debug("session_pty_req: session %d alloc %s", s
->self
, s
->tty
);
1954 /* for SSH1 the tty modes length is not given */
1956 n_bytes
= packet_remaining();
1957 tty_parse_modes(s
->ttyfd
, &n_bytes
);
1960 pty_setowner(s
->pw
, s
->tty
);
1962 /* Set window size from the packet. */
1963 pty_change_window_size(s
->ptyfd
, s
->row
, s
->col
, s
->xpixel
, s
->ypixel
);
1966 session_proctitle(s
);
1971 session_subsystem_req(Session
*s
)
1976 char *prog
, *cmd
, *subsys
= packet_get_string(&len
);
1980 logit("subsystem request for %.100s", subsys
);
1982 for (i
= 0; i
< options
.num_subsystems
; i
++) {
1983 if (strcmp(subsys
, options
.subsystem_name
[i
]) == 0) {
1984 prog
= options
.subsystem_command
[i
];
1985 cmd
= options
.subsystem_args
[i
];
1986 if (!strcmp(INTERNAL_SFTP_NAME
, prog
)) {
1987 s
->is_subsystem
= SUBSYSTEM_INT_SFTP
;
1988 } else if (stat(prog
, &st
) < 0) {
1989 error("subsystem: cannot stat %s: %s", prog
,
1993 s
->is_subsystem
= SUBSYSTEM_EXT
;
1995 debug("subsystem: exec() %s", cmd
);
2003 logit("subsystem request for %.100s failed, subsystem not found",
2011 session_x11_req(Session
*s
)
2015 if (s
->auth_proto
!= NULL
|| s
->auth_data
!= NULL
) {
2016 error("session_x11_req: session %d: "
2017 "x11 forwarding already active", s
->self
);
2020 s
->single_connection
= packet_get_char();
2021 s
->auth_proto
= packet_get_string(NULL
);
2022 s
->auth_data
= packet_get_string(NULL
);
2023 s
->screen
= packet_get_int();
2026 success
= session_setup_x11fwd(s
);
2028 xfree(s
->auth_proto
);
2029 xfree(s
->auth_data
);
2030 s
->auth_proto
= NULL
;
2031 s
->auth_data
= NULL
;
2037 session_shell_req(Session
*s
)
2045 session_exec_req(Session
*s
)
2048 char *command
= packet_get_string(&len
);
2050 do_exec(s
, command
);
2056 session_break_req(Session
*s
)
2059 packet_get_int(); /* ignored */
2062 if (s
->ttyfd
== -1 ||
2063 tcsendbreak(s
->ttyfd
, 0) < 0)
2069 session_env_req(Session
*s
)
2072 u_int name_len
, val_len
, i
;
2074 name
= packet_get_string(&name_len
);
2075 val
= packet_get_string(&val_len
);
2078 /* Don't set too many environment variables */
2079 if (s
->num_env
> 128) {
2080 debug2("Ignoring env request %s: too many env vars", name
);
2084 for (i
= 0; i
< options
.num_accept_env
; i
++) {
2085 if (match_pattern(name
, options
.accept_env
[i
])) {
2086 debug2("Setting env %d: %s=%s", s
->num_env
, name
, val
);
2087 s
->env
= xrealloc(s
->env
, s
->num_env
+ 1,
2089 s
->env
[s
->num_env
].name
= name
;
2090 s
->env
[s
->num_env
].val
= val
;
2095 debug2("Ignoring env request %s: disallowed name", name
);
2104 session_auth_agent_req(Session
*s
)
2106 static int called
= 0;
2108 if (no_agent_forwarding_flag
) {
2109 debug("session_auth_agent_req: no_agent_forwarding_flag");
2116 return auth_input_request_forwarding(s
->pw
);
2121 session_input_channel_req(Channel
*c
, const char *rtype
)
2126 if ((s
= session_by_channel(c
->self
)) == NULL
) {
2127 logit("session_input_channel_req: no session %d req %.100s",
2131 debug("session_input_channel_req: session %d req %s", s
->self
, rtype
);
2134 * a session is in LARVAL state until a shell, a command
2135 * or a subsystem is executed
2137 if (c
->type
== SSH_CHANNEL_LARVAL
) {
2138 if (strcmp(rtype
, "shell") == 0) {
2139 success
= session_shell_req(s
);
2140 } else if (strcmp(rtype
, "exec") == 0) {
2141 success
= session_exec_req(s
);
2142 } else if (strcmp(rtype
, "pty-req") == 0) {
2143 success
= session_pty_req(s
);
2144 } else if (strcmp(rtype
, "x11-req") == 0) {
2145 success
= session_x11_req(s
);
2146 } else if (strcmp(rtype
, "auth-agent-req@openssh.com") == 0) {
2147 success
= session_auth_agent_req(s
);
2148 } else if (strcmp(rtype
, "subsystem") == 0) {
2149 success
= session_subsystem_req(s
);
2150 } else if (strcmp(rtype
, "env") == 0) {
2151 success
= session_env_req(s
);
2154 if (strcmp(rtype
, "window-change") == 0) {
2155 success
= session_window_change_req(s
);
2156 } else if (strcmp(rtype
, "break") == 0) {
2157 success
= session_break_req(s
);
2164 session_set_fds(Session
*s
, int fdin
, int fdout
, int fderr
)
2167 fatal("session_set_fds: called for proto != 2.0");
2169 * now that have a child and a pipe to the child,
2170 * we can activate our channel and register the fd's
2172 if (s
->chanid
== -1)
2173 fatal("no channel for session %d", s
->self
);
2174 channel_set_fds(s
->chanid
,
2176 fderr
== -1 ? CHAN_EXTENDED_IGNORE
: CHAN_EXTENDED_READ
,
2178 CHAN_SES_WINDOW_DEFAULT
);
2182 * Function to perform pty cleanup. Also called if we get aborted abnormally
2183 * (e.g., due to a dropped connection).
2186 session_pty_cleanup2(Session
*s
)
2189 error("session_pty_cleanup: no session");
2195 debug("session_pty_cleanup: session %d release %s", s
->self
, s
->tty
);
2197 /* Record that the user has logged out. */
2199 record_logout(s
->pid
, s
->tty
, s
->pw
->pw_name
);
2201 /* Release the pseudo-tty. */
2203 pty_release(s
->tty
);
2206 * Close the server side of the socket pairs. We must do this after
2207 * the pty cleanup, so that another process doesn't get this pty
2208 * while we're still cleaning up.
2210 if (close(s
->ptymaster
) < 0)
2211 error("close(s->ptymaster/%d): %s", s
->ptymaster
, strerror(errno
));
2213 /* unlink pty from session */
2218 session_pty_cleanup(Session
*s
)
2220 PRIVSEP(session_pty_cleanup2(s
));
2226 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2241 return "SIG@openssh.com";
2245 session_close_x11(int id
)
2249 if ((c
= channel_by_id(id
)) == NULL
) {
2250 debug("session_close_x11: x11 channel %d missing", id
);
2252 /* Detach X11 listener */
2253 debug("session_close_x11: detach x11 channel %d", id
);
2254 channel_cancel_cleanup(id
);
2255 if (c
->ostate
!= CHAN_OUTPUT_CLOSED
)
2261 session_close_single_x11(int id
, void *arg
)
2266 debug3("session_close_single_x11: channel %d", id
);
2267 channel_cancel_cleanup(id
);
2268 if ((s
= session_by_x11_channel(id
)) == NULL
)
2269 fatal("session_close_single_x11: no x11 channel %d", id
);
2270 for (i
= 0; s
->x11_chanids
[i
] != -1; i
++) {
2271 debug("session_close_single_x11: session %d: "
2272 "closing channel %d", s
->self
, s
->x11_chanids
[i
]);
2274 * The channel "id" is already closing, but make sure we
2275 * close all of its siblings.
2277 if (s
->x11_chanids
[i
] != id
)
2278 session_close_x11(s
->x11_chanids
[i
]);
2280 xfree(s
->x11_chanids
);
2281 s
->x11_chanids
= NULL
;
2286 if (s
->auth_proto
) {
2287 xfree(s
->auth_proto
);
2288 s
->auth_proto
= NULL
;
2291 xfree(s
->auth_data
);
2292 s
->auth_data
= NULL
;
2294 if (s
->auth_display
) {
2295 xfree(s
->auth_display
);
2296 s
->auth_display
= NULL
;
2301 session_exit_message(Session
*s
, int status
)
2305 if ((c
= channel_lookup(s
->chanid
)) == NULL
)
2306 fatal("session_exit_message: session %d: no channel %d",
2307 s
->self
, s
->chanid
);
2308 debug("session_exit_message: session %d channel %d pid %ld",
2309 s
->self
, s
->chanid
, (long)s
->pid
);
2311 if (WIFEXITED(status
)) {
2312 channel_request_start(s
->chanid
, "exit-status", 0);
2313 packet_put_int(WEXITSTATUS(status
));
2315 } else if (WIFSIGNALED(status
)) {
2316 channel_request_start(s
->chanid
, "exit-signal", 0);
2317 packet_put_cstring(sig2name(WTERMSIG(status
)));
2319 packet_put_char(WCOREDUMP(status
));
2320 #else /* WCOREDUMP */
2322 #endif /* WCOREDUMP */
2323 packet_put_cstring("");
2324 packet_put_cstring("");
2327 /* Some weird exit cause. Just exit. */
2328 packet_disconnect("wait returned status %04x.", status
);
2331 /* disconnect channel */
2332 debug("session_exit_message: release channel %d", s
->chanid
);
2335 * Adjust cleanup callback attachment to send close messages when
2336 * the channel gets EOF. The session will be then be closed
2337 * by session_close_by_channel when the childs close their fds.
2339 channel_register_cleanup(c
->self
, session_close_by_channel
, 1);
2342 * emulate a write failure with 'chan_write_failed', nobody will be
2343 * interested in data we write.
2344 * Note that we must not call 'chan_read_failed', since there could
2345 * be some more data waiting in the pipe.
2347 if (c
->ostate
!= CHAN_OUTPUT_CLOSED
)
2348 chan_write_failed(c
);
2352 session_close(Session
*s
)
2356 debug("session_close: session %d pid %ld", s
->self
, (long)s
->pid
);
2358 session_pty_cleanup(s
);
2364 xfree(s
->x11_chanids
);
2365 if (s
->auth_display
)
2366 xfree(s
->auth_display
);
2368 xfree(s
->auth_data
);
2370 xfree(s
->auth_proto
);
2372 if (s
->env
!= NULL
) {
2373 for (i
= 0; i
< s
->num_env
; i
++) {
2374 xfree(s
->env
[i
].name
);
2375 xfree(s
->env
[i
].val
);
2379 session_proctitle(s
);
2383 session_close_by_pid(pid_t pid
, int status
)
2385 Session
*s
= session_by_pid(pid
);
2387 debug("session_close_by_pid: no session for pid %ld",
2391 if (s
->chanid
!= -1)
2392 session_exit_message(s
, status
);
2394 session_pty_cleanup(s
);
2399 * this is called when a channel dies before
2400 * the session 'child' itself dies
2403 session_close_by_channel(int id
, void *arg
)
2405 Session
*s
= session_by_channel(id
);
2409 debug("session_close_by_channel: no session for id %d", id
);
2412 debug("session_close_by_channel: channel %d child %ld",
2415 debug("session_close_by_channel: channel %d: has child", id
);
2417 * delay detach of session, but release pty, since
2418 * the fd's to the child are already closed
2421 session_pty_cleanup(s
);
2424 /* detach by removing callback */
2425 channel_cancel_cleanup(s
->chanid
);
2427 /* Close any X11 listeners associated with this session */
2428 if (s
->x11_chanids
!= NULL
) {
2429 for (i
= 0; s
->x11_chanids
[i
] != -1; i
++) {
2430 session_close_x11(s
->x11_chanids
[i
]);
2431 s
->x11_chanids
[i
] = -1;
2440 session_destroy_all(void (*closefunc
)(Session
*))
2443 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
2444 Session
*s
= &sessions
[i
];
2446 if (closefunc
!= NULL
)
2455 session_tty_list(void)
2457 static char buf
[1024];
2462 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
2463 Session
*s
= &sessions
[i
];
2464 if (s
->used
&& s
->ttyfd
!= -1) {
2466 if (strncmp(s
->tty
, "/dev/", 5) != 0) {
2467 cp
= strrchr(s
->tty
, '/');
2468 cp
= (cp
== NULL
) ? s
->tty
: cp
+ 1;
2473 strlcat(buf
, ",", sizeof buf
);
2474 strlcat(buf
, cp
, sizeof buf
);
2478 strlcpy(buf
, "notty", sizeof buf
);
2483 session_proctitle(Session
*s
)
2486 error("no user for session %d", s
->self
);
2488 setproctitle("%s@%s", s
->pw
->pw_name
, session_tty_list());
2492 session_setup_x11fwd(Session
*s
)
2495 char display
[512], auth_display
[512];
2496 char hostname
[MAXHOSTNAMELEN
];
2499 if (no_x11_forwarding_flag
) {
2500 packet_send_debug("X11 forwarding disabled in user configuration file.");
2503 if (!options
.x11_forwarding
) {
2504 debug("X11 forwarding disabled in server configuration file.");
2507 if (!options
.xauth_location
||
2508 (stat(options
.xauth_location
, &st
) == -1)) {
2509 packet_send_debug("No xauth program; cannot forward with spoofing.");
2512 if (options
.use_login
) {
2513 packet_send_debug("X11 forwarding disabled; "
2514 "not compatible with UseLogin=yes.");
2517 if (s
->display
!= NULL
) {
2518 debug("X11 display already set.");
2521 if (x11_create_display_inet(options
.x11_display_offset
,
2522 options
.x11_use_localhost
, s
->single_connection
,
2523 &s
->display_number
, &s
->x11_chanids
) == -1) {
2524 debug("x11_create_display_inet failed.");
2527 for (i
= 0; s
->x11_chanids
[i
] != -1; i
++) {
2528 channel_register_cleanup(s
->x11_chanids
[i
],
2529 session_close_single_x11
, 0);
2532 /* Set up a suitable value for the DISPLAY variable. */
2533 if (gethostname(hostname
, sizeof(hostname
)) < 0)
2534 fatal("gethostname: %.100s", strerror(errno
));
2536 * auth_display must be used as the displayname when the
2537 * authorization entry is added with xauth(1). This will be
2538 * different than the DISPLAY string for localhost displays.
2540 if (options
.x11_use_localhost
) {
2541 snprintf(display
, sizeof display
, "localhost:%u.%u",
2542 s
->display_number
, s
->screen
);
2543 snprintf(auth_display
, sizeof auth_display
, "unix:%u.%u",
2544 s
->display_number
, s
->screen
);
2545 s
->display
= xstrdup(display
);
2546 s
->auth_display
= xstrdup(auth_display
);
2548 #ifdef IPADDR_IN_DISPLAY
2550 struct in_addr my_addr
;
2552 he
= gethostbyname(hostname
);
2554 error("Can't get IP address for X11 DISPLAY.");
2555 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2558 memcpy(&my_addr
, he
->h_addr_list
[0], sizeof(struct in_addr
));
2559 snprintf(display
, sizeof display
, "%.50s:%u.%u", inet_ntoa(my_addr
),
2560 s
->display_number
, s
->screen
);
2562 snprintf(display
, sizeof display
, "%.400s:%u.%u", hostname
,
2563 s
->display_number
, s
->screen
);
2565 s
->display
= xstrdup(display
);
2566 s
->auth_display
= xstrdup(display
);
2573 do_authenticated2(Authctxt
*authctxt
)
2575 server_loop2(authctxt
);
2579 do_cleanup(Authctxt
*authctxt
)
2581 static int called
= 0;
2583 debug("do_cleanup");
2585 /* no cleanup if we're in the child for login shell */
2589 /* avoid double cleanup */
2594 if (authctxt
== NULL
)
2598 if (options
.use_pam
) {
2600 sshpam_thread_cleanup();
2604 if (!authctxt
->authenticated
)
2608 if (options
.kerberos_ticket_cleanup
&&
2610 krb5_cleanup_proc(authctxt
);
2614 if (compat20
&& options
.gss_cleanup_creds
)
2615 ssh_gssapi_cleanup_creds();
2618 /* remove agent socket */
2619 auth_sock_cleanup_proc(authctxt
->pw
);
2622 * Cleanup ptys/utmp only if privsep is disabled,
2623 * or if running in monitor.
2625 if (!use_privsep
|| mm_is_monitor())
2626 session_destroy_all(session_pty_cleanup2
);