1 /* $OpenBSD: session.c,v 1.233 2008/03/26 21:28:14 djm Exp $ */
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * As far as I am concerned, the code I have written for this software
7 * can be used freely for any purpose. Any derived versions of this
8 * software must be clearly marked as such, and if the derived work is
9 * incompatible with the protocol description in the RFC file, it must be
10 * called by a name other than "ssh" or "Secure Shell".
12 * SSH2 support by Markus Friedl.
13 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
24 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #ifdef HAVE_SYS_STAT_H
41 # include <sys/stat.h>
43 #include <sys/socket.h>
47 #include <arpa/inet.h>
80 #include "auth-options.h"
81 #include "pathnames.h"
85 #include "serverloop.h"
90 #include "monitor_wrap.h"
93 #if defined(KRB5) && defined(USE_AFS)
99 Session
*session_new(void);
100 void session_set_fds(Session
*, int, int, int);
101 void session_pty_cleanup(Session
*);
102 void session_proctitle(Session
*);
103 int session_setup_x11fwd(Session
*);
104 void do_exec_pty(Session
*, const char *);
105 void do_exec_no_pty(Session
*, const char *);
106 void do_exec(Session
*, const char *);
107 void do_login(Session
*, const char *);
108 #ifdef LOGIN_NEEDS_UTMPX
109 static void do_pre_login(Session
*s
);
111 void do_child(Session
*, const char *);
113 int check_quietlogin(Session
*, const char *);
115 static void do_authenticated1(Authctxt
*);
116 static void do_authenticated2(Authctxt
*);
118 static int session_pty_req(Session
*);
121 extern ServerOptions options
;
122 extern char *__progname
;
123 extern int log_stderr
;
124 extern int debug_flag
;
125 extern u_int utmp_len
;
126 extern int startup_pipe
;
127 extern void destroy_sensitive_data(void);
128 extern Buffer loginmsg
;
130 /* original command from peer. */
131 const char *original_command
= NULL
;
134 #define MAX_SESSIONS 20
135 Session sessions
[MAX_SESSIONS
];
137 #define SUBSYSTEM_NONE 0
138 #define SUBSYSTEM_EXT 1
139 #define SUBSYSTEM_INT_SFTP 2
141 #ifdef HAVE_LOGIN_CAP
145 static int is_child
= 0;
147 /* Name and directory of socket for authentication agent forwarding. */
148 static char *auth_sock_name
= NULL
;
149 static char *auth_sock_dir
= NULL
;
151 /* removes the agent forwarding socket */
154 auth_sock_cleanup_proc(struct passwd
*pw
)
156 if (auth_sock_name
!= NULL
) {
157 temporarily_use_uid(pw
);
158 unlink(auth_sock_name
);
159 rmdir(auth_sock_dir
);
160 auth_sock_name
= NULL
;
166 auth_input_request_forwarding(struct passwd
* pw
)
170 struct sockaddr_un sunaddr
;
172 if (auth_sock_name
!= NULL
) {
173 error("authentication forwarding requested twice.");
177 /* Temporarily drop privileged uid for mkdir/bind. */
178 temporarily_use_uid(pw
);
180 /* Allocate a buffer for the socket name, and format the name. */
181 auth_sock_name
= xmalloc(MAXPATHLEN
);
182 auth_sock_dir
= xmalloc(MAXPATHLEN
);
183 strlcpy(auth_sock_dir
, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN
);
185 /* Create private directory for socket */
186 if (mkdtemp(auth_sock_dir
) == NULL
) {
187 packet_send_debug("Agent forwarding disabled: "
188 "mkdtemp() failed: %.100s", strerror(errno
));
190 xfree(auth_sock_name
);
191 xfree(auth_sock_dir
);
192 auth_sock_name
= NULL
;
193 auth_sock_dir
= NULL
;
196 snprintf(auth_sock_name
, MAXPATHLEN
, "%s/agent.%ld",
197 auth_sock_dir
, (long) getpid());
199 /* Create the socket. */
200 sock
= socket(AF_UNIX
, SOCK_STREAM
, 0);
202 packet_disconnect("socket: %.100s", strerror(errno
));
204 /* Bind it to the name. */
205 memset(&sunaddr
, 0, sizeof(sunaddr
));
206 sunaddr
.sun_family
= AF_UNIX
;
207 strlcpy(sunaddr
.sun_path
, auth_sock_name
, sizeof(sunaddr
.sun_path
));
209 if (bind(sock
, (struct sockaddr
*)&sunaddr
, sizeof(sunaddr
)) < 0)
210 packet_disconnect("bind: %.100s", strerror(errno
));
212 /* Restore the privileged uid. */
215 /* Start listening on the socket. */
216 if (listen(sock
, SSH_LISTEN_BACKLOG
) < 0)
217 packet_disconnect("listen: %.100s", strerror(errno
));
219 /* Allocate a channel for the authentication agent socket. */
220 nc
= channel_new("auth socket",
221 SSH_CHANNEL_AUTH_SOCKET
, sock
, sock
, -1,
222 CHAN_X11_WINDOW_DEFAULT
, CHAN_X11_PACKET_DEFAULT
,
223 0, "auth socket", 1);
224 strlcpy(nc
->path
, auth_sock_name
, sizeof(nc
->path
));
229 display_loginmsg(void)
231 if (buffer_len(&loginmsg
) > 0) {
232 buffer_append(&loginmsg
, "\0", 1);
233 printf("%s", (char *)buffer_ptr(&loginmsg
));
234 buffer_clear(&loginmsg
);
239 do_authenticated(Authctxt
*authctxt
)
241 setproctitle("%s", authctxt
->pw
->pw_name
);
243 /* setup the channel layer */
244 if (!no_port_forwarding_flag
&& options
.allow_tcp_forwarding
)
245 channel_permit_all_opens();
248 do_authenticated2(authctxt
);
250 do_authenticated1(authctxt
);
252 do_cleanup(authctxt
);
256 * Prepares for an interactive session. This is called after the user has
257 * been successfully authenticated. During this message exchange, pseudo
258 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
259 * are requested, etc.
262 do_authenticated1(Authctxt
*authctxt
)
266 int success
, type
, screen_flag
;
267 int enable_compression_after_reply
= 0;
268 u_int proto_len
, data_len
, dlen
, compression_level
= 0;
272 error("no more sessions");
275 s
->authctxt
= authctxt
;
276 s
->pw
= authctxt
->pw
;
279 * We stay in this loop until the client requests to execute a shell
285 /* Get a packet from the client. */
286 type
= packet_read();
288 /* Process the packet. */
290 case SSH_CMSG_REQUEST_COMPRESSION
:
291 compression_level
= packet_get_int();
293 if (compression_level
< 1 || compression_level
> 9) {
294 packet_send_debug("Received invalid compression level %d.",
298 if (options
.compression
== COMP_NONE
) {
299 debug2("compression disabled");
302 /* Enable compression after we have responded with SUCCESS. */
303 enable_compression_after_reply
= 1;
307 case SSH_CMSG_REQUEST_PTY
:
308 success
= session_pty_req(s
);
311 case SSH_CMSG_X11_REQUEST_FORWARDING
:
312 s
->auth_proto
= packet_get_string(&proto_len
);
313 s
->auth_data
= packet_get_string(&data_len
);
315 screen_flag
= packet_get_protocol_flags() &
316 SSH_PROTOFLAG_SCREEN_NUMBER
;
317 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag
);
319 if (packet_remaining() == 4) {
321 debug2("Buggy client: "
322 "X11 screen flag missing");
323 s
->screen
= packet_get_int();
328 success
= session_setup_x11fwd(s
);
330 xfree(s
->auth_proto
);
332 s
->auth_proto
= NULL
;
337 case SSH_CMSG_AGENT_REQUEST_FORWARDING
:
338 if (no_agent_forwarding_flag
|| compat13
) {
339 debug("Authentication agent forwarding not permitted for this authentication.");
342 debug("Received authentication agent forwarding request.");
343 success
= auth_input_request_forwarding(s
->pw
);
346 case SSH_CMSG_PORT_FORWARD_REQUEST
:
347 if (no_port_forwarding_flag
) {
348 debug("Port forwarding not permitted for this authentication.");
351 if (!options
.allow_tcp_forwarding
) {
352 debug("Port forwarding not permitted.");
355 debug("Received TCP/IP port forwarding request.");
356 if (channel_input_port_forward_request(s
->pw
->pw_uid
== 0,
357 options
.gateway_ports
) < 0) {
358 debug("Port forwarding failed.");
364 case SSH_CMSG_MAX_PACKET_SIZE
:
365 if (packet_set_maxsize(packet_get_int()) > 0)
369 case SSH_CMSG_EXEC_SHELL
:
370 case SSH_CMSG_EXEC_CMD
:
371 if (type
== SSH_CMSG_EXEC_CMD
) {
372 command
= packet_get_string(&dlen
);
373 debug("Exec command '%.500s'", command
);
385 * Any unknown messages in this phase are ignored,
386 * and a failure message is returned.
388 logit("Unknown packet type received after authentication: %d", type
);
390 packet_start(success
? SSH_SMSG_SUCCESS
: SSH_SMSG_FAILURE
);
394 /* Enable compression now that we have replied if appropriate. */
395 if (enable_compression_after_reply
) {
396 enable_compression_after_reply
= 0;
397 packet_start_compression(compression_level
);
403 * This is called to fork and execute a command when we have no tty. This
404 * will call do_child from the child, and server_loop from the parent after
405 * setting up file descriptors and such.
408 do_exec_no_pty(Session
*s
, const char *command
)
413 int pin
[2], pout
[2], perr
[2];
414 /* Allocate pipes for communicating with the program. */
415 if (pipe(pin
) < 0 || pipe(pout
) < 0 || pipe(perr
) < 0)
416 packet_disconnect("Could not create pipes: %.100s",
418 #else /* USE_PIPES */
419 int inout
[2], err
[2];
420 /* Uses socket pairs to communicate with the program. */
421 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, inout
) < 0 ||
422 socketpair(AF_UNIX
, SOCK_STREAM
, 0, err
) < 0)
423 packet_disconnect("Could not create socket pairs: %.100s",
425 #endif /* USE_PIPES */
427 fatal("do_exec_no_pty: no session");
429 session_proctitle(s
);
431 /* Fork the child. */
432 if ((pid
= fork()) == 0) {
435 /* Child. Reinitialize the log since the pid has changed. */
436 log_init(__progname
, options
.log_level
, options
.log_facility
, log_stderr
);
439 * Create a new session and process group since the 4.4BSD
440 * setlogin() affects the entire process group.
443 error("setsid failed: %.100s", strerror(errno
));
447 * Redirect stdin. We close the parent side of the socket
448 * pair, and make the child side the standard input.
451 if (dup2(pin
[0], 0) < 0)
452 perror("dup2 stdin");
455 /* Redirect stdout. */
457 if (dup2(pout
[1], 1) < 0)
458 perror("dup2 stdout");
461 /* Redirect stderr. */
463 if (dup2(perr
[1], 2) < 0)
464 perror("dup2 stderr");
466 #else /* USE_PIPES */
468 * Redirect stdin, stdout, and stderr. Stdin and stdout will
469 * use the same socket, as some programs (particularly rdist)
470 * seem to depend on it.
474 if (dup2(inout
[0], 0) < 0) /* stdin */
475 perror("dup2 stdin");
476 if (dup2(inout
[0], 1) < 0) /* stdout. Note: same socket as stdin. */
477 perror("dup2 stdout");
478 if (dup2(err
[0], 2) < 0) /* stderr */
479 perror("dup2 stderr");
480 #endif /* USE_PIPES */
483 cray_init_job(s
->pw
); /* set up cray jid and tmpdir */
486 /* Do processing for the child (exec command etc). */
487 do_child(s
, command
);
491 signal(WJSIGNAL
, cray_job_termination_handler
);
495 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE
);
498 packet_disconnect("fork failed: %.100s", strerror(errno
));
500 /* Set interactive/non-interactive mode. */
501 packet_set_interactive(s
->display
!= NULL
);
503 /* We are the parent. Close the child sides of the pipes. */
509 if (s
->is_subsystem
) {
513 session_set_fds(s
, pin
[1], pout
[0], perr
[0]);
515 /* Enter the interactive session. */
516 server_loop(pid
, pin
[1], pout
[0], perr
[0]);
517 /* server_loop has closed pin[1], pout[0], and perr[0]. */
519 #else /* USE_PIPES */
520 /* We are the parent. Close the child sides of the socket pairs. */
525 * Clear loginmsg, since it's the child's responsibility to display
526 * it to the user, otherwise multiple sessions may accumulate
527 * multiple copies of the login messages.
529 buffer_clear(&loginmsg
);
532 * Enter the interactive session. Note: server_loop must be able to
533 * handle the case that fdin and fdout are the same.
536 session_set_fds(s
, inout
[1], inout
[1], s
->is_subsystem
? -1 : err
[1]);
538 server_loop(pid
, inout
[1], inout
[1], err
[1]);
539 /* server_loop has closed inout[1] and err[1]. */
541 #endif /* USE_PIPES */
545 * This is called to fork and execute a command when we have a tty. This
546 * will call do_child from the child, and server_loop from the parent after
547 * setting up file descriptors, controlling tty, updating wtmp, utmp,
548 * lastlog, and other such operations.
551 do_exec_pty(Session
*s
, const char *command
)
553 int fdout
, ptyfd
, ttyfd
, ptymaster
;
557 fatal("do_exec_pty: no session");
561 /* Fork the child. */
562 if ((pid
= fork()) == 0) {
565 /* Child. Reinitialize the log because the pid has changed. */
566 log_init(__progname
, options
.log_level
, options
.log_facility
, log_stderr
);
567 /* Close the master side of the pseudo tty. */
570 /* Make the pseudo tty our controlling tty. */
571 pty_make_controlling_tty(&ttyfd
, s
->tty
);
573 /* Redirect stdin/stdout/stderr from the pseudo tty. */
574 if (dup2(ttyfd
, 0) < 0)
575 error("dup2 stdin: %s", strerror(errno
));
576 if (dup2(ttyfd
, 1) < 0)
577 error("dup2 stdout: %s", strerror(errno
));
578 if (dup2(ttyfd
, 2) < 0)
579 error("dup2 stderr: %s", strerror(errno
));
581 /* Close the extra descriptor for the pseudo tty. */
584 /* record login, etc. similar to login(1) */
586 if (!(options
.use_login
&& command
== NULL
)) {
588 cray_init_job(s
->pw
); /* set up cray jid and tmpdir */
590 do_login(s
, command
);
592 # ifdef LOGIN_NEEDS_UTMPX
598 /* Do common processing for the child, such as execing the command. */
599 do_child(s
, command
);
603 signal(WJSIGNAL
, cray_job_termination_handler
);
607 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE
);
610 packet_disconnect("fork failed: %.100s", strerror(errno
));
613 /* Parent. Close the slave side of the pseudo tty. */
617 * Create another descriptor of the pty master side for use as the
618 * standard input. We could use the original descriptor, but this
619 * simplifies code in server_loop. The descriptor is bidirectional.
623 packet_disconnect("dup #1 failed: %.100s", strerror(errno
));
625 /* we keep a reference to the pty master */
626 ptymaster
= dup(ptyfd
);
628 packet_disconnect("dup #2 failed: %.100s", strerror(errno
));
629 s
->ptymaster
= ptymaster
;
631 /* Enter interactive session. */
632 packet_set_interactive(1);
634 session_set_fds(s
, ptyfd
, fdout
, -1);
636 server_loop(pid
, ptyfd
, fdout
, -1);
637 /* server_loop _has_ closed ptyfd and fdout. */
641 #ifdef LOGIN_NEEDS_UTMPX
643 do_pre_login(Session
*s
)
646 struct sockaddr_storage from
;
647 pid_t pid
= getpid();
650 * Get IP address of client. If the connection is not a socket, let
651 * the address be 0.0.0.0.
653 memset(&from
, 0, sizeof(from
));
654 fromlen
= sizeof(from
);
655 if (packet_connection_is_on_socket()) {
656 if (getpeername(packet_get_connection_in(),
657 (struct sockaddr
*)&from
, &fromlen
) < 0) {
658 debug("getpeername: %.100s", strerror(errno
));
663 record_utmp_only(pid
, s
->tty
, s
->pw
->pw_name
,
664 get_remote_name_or_ip(utmp_len
, options
.use_dns
),
665 (struct sockaddr
*)&from
, fromlen
);
670 * This is called to fork and execute a command. If another command is
671 * to be forced, execute that instead.
674 do_exec(Session
*s
, const char *command
)
676 if (options
.adm_forced_command
) {
677 original_command
= command
;
678 command
= options
.adm_forced_command
;
679 if (strcmp(INTERNAL_SFTP_NAME
, command
) == 0)
680 s
->is_subsystem
= SUBSYSTEM_INT_SFTP
;
681 else if (s
->is_subsystem
)
682 s
->is_subsystem
= SUBSYSTEM_EXT
;
683 debug("Forced command (config) '%.900s'", command
);
684 } else if (forced_command
) {
685 original_command
= command
;
686 command
= forced_command
;
687 if (strcmp(INTERNAL_SFTP_NAME
, command
) == 0)
688 s
->is_subsystem
= SUBSYSTEM_INT_SFTP
;
689 else if (s
->is_subsystem
)
690 s
->is_subsystem
= SUBSYSTEM_EXT
;
691 debug("Forced command (key option) '%.900s'", command
);
694 #ifdef SSH_AUDIT_EVENTS
696 PRIVSEP(audit_run_command(command
));
697 else if (s
->ttyfd
== -1) {
698 char *shell
= s
->pw
->pw_shell
;
700 if (shell
[0] == '\0') /* empty shell means /bin/sh */
702 PRIVSEP(audit_run_command(shell
));
706 do_exec_pty(s
, command
);
708 do_exec_no_pty(s
, command
);
710 original_command
= NULL
;
713 * Clear loginmsg: it's the child's responsibility to display
714 * it to the user, otherwise multiple sessions may accumulate
715 * multiple copies of the login messages.
717 buffer_clear(&loginmsg
);
720 /* administrative, login(1)-like work */
722 do_login(Session
*s
, const char *command
)
725 struct sockaddr_storage from
;
726 struct passwd
* pw
= s
->pw
;
727 pid_t pid
= getpid();
730 * Get IP address of client. If the connection is not a socket, let
731 * the address be 0.0.0.0.
733 memset(&from
, 0, sizeof(from
));
734 fromlen
= sizeof(from
);
735 if (packet_connection_is_on_socket()) {
736 if (getpeername(packet_get_connection_in(),
737 (struct sockaddr
*) & from
, &fromlen
) < 0) {
738 debug("getpeername: %.100s", strerror(errno
));
743 /* Record that there was a login on that tty from the remote host. */
745 record_login(pid
, s
->tty
, pw
->pw_name
, pw
->pw_uid
,
746 get_remote_name_or_ip(utmp_len
,
748 (struct sockaddr
*)&from
, fromlen
);
752 * If password change is needed, do it now.
753 * This needs to occur before the ~/.hushlogin check.
755 if (options
.use_pam
&& !use_privsep
&& s
->authctxt
->force_pwchange
) {
758 s
->authctxt
->force_pwchange
= 0;
759 /* XXX - signal [net] parent to enable forwardings */
763 if (check_quietlogin(s
, command
))
772 * Display the message of the day.
779 #ifdef HAVE_LOGIN_CAP
783 #ifdef HAVE_LOGIN_CAP
784 fname
= login_getcapstr(lc
, "copyright", NULL
, NULL
);
785 if (fname
!= NULL
&& (f
= fopen(fname
, "r")) != NULL
) {
786 while (fgets(buf
, sizeof(buf
), f
) != NULL
)
790 #endif /* HAVE_LOGIN_CAP */
791 (void)printf("%s\n\t%s %s\n",
792 "Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
793 "The Regents of the University of California. ",
794 "All rights reserved.");
798 if (options
.print_motd
) {
799 #ifdef HAVE_LOGIN_CAP
800 f
= fopen(login_getcapstr(lc
, "welcome", "/etc/motd",
803 f
= fopen("/etc/motd", "r");
806 while (fgets(buf
, sizeof(buf
), f
))
815 * Check for quiet login, either .hushlogin or command given.
818 check_quietlogin(Session
*s
, const char *command
)
821 struct passwd
*pw
= s
->pw
;
824 /* Return 1 if .hushlogin exists or a command given. */
827 snprintf(buf
, sizeof(buf
), "%.200s/.hushlogin", pw
->pw_dir
);
828 #ifdef HAVE_LOGIN_CAP
829 if (login_getcapbool(lc
, "hushlogin", 0) || stat(buf
, &st
) >= 0)
832 if (stat(buf
, &st
) >= 0)
839 * Sets the value of the given variable in the environment. If the variable
840 * already exists, its value is overriden.
843 child_set_env(char ***envp
, u_int
*envsizep
, const char *name
,
851 * If we're passed an uninitialized list, allocate a single null
852 * entry before continuing.
854 if (*envp
== NULL
&& *envsizep
== 0) {
855 *envp
= xmalloc(sizeof(char *));
861 * Find the slot where the value should be stored. If the variable
862 * already exists, we reuse the slot; otherwise we append a new slot
863 * at the end of the array, expanding if necessary.
866 namelen
= strlen(name
);
867 for (i
= 0; env
[i
]; i
++)
868 if (strncmp(env
[i
], name
, namelen
) == 0 && env
[i
][namelen
] == '=')
871 /* Reuse the slot. */
874 /* New variable. Expand if necessary. */
876 if (i
>= envsize
- 1) {
878 fatal("child_set_env: too many env vars");
880 env
= (*envp
) = xrealloc(env
, envsize
, sizeof(char *));
883 /* Need to set the NULL pointer at end of array beyond the new slot. */
887 /* Allocate space and format the variable in the appropriate slot. */
888 env
[i
] = xmalloc(strlen(name
) + 1 + strlen(value
) + 1);
889 snprintf(env
[i
], strlen(name
) + 1 + strlen(value
) + 1, "%s=%s", name
, value
);
893 * Reads environment variables from the given file and adds/overrides them
894 * into the environment. If the file does not exist, this does nothing.
895 * Otherwise, it must consist of empty lines, comments (line starts with '#')
896 * and assignments of the form name=value. No other forms are allowed.
899 read_environment_file(char ***env
, u_int
*envsize
,
900 const char *filename
)
907 f
= fopen(filename
, "r");
911 while (fgets(buf
, sizeof(buf
), f
)) {
913 fatal("Too many lines in environment file %s", filename
);
914 for (cp
= buf
; *cp
== ' ' || *cp
== '\t'; cp
++)
916 if (!*cp
|| *cp
== '#' || *cp
== '\n')
919 cp
[strcspn(cp
, "\n")] = '\0';
921 value
= strchr(cp
, '=');
923 fprintf(stderr
, "Bad line %u in %.100s\n", lineno
,
928 * Replace the equals sign by nul, and advance value to
933 child_set_env(env
, envsize
, cp
, value
);
938 #ifdef HAVE_ETC_DEFAULT_LOGIN
940 * Return named variable from specified environment, or NULL if not present.
943 child_get_env(char **env
, const char *name
)
949 for (i
=0; env
[i
] != NULL
; i
++)
950 if (strncmp(name
, env
[i
], len
) == 0 && env
[i
][len
] == '=')
951 return(env
[i
] + len
+ 1);
956 * Read /etc/default/login.
957 * We pick up the PATH (or SUPATH for root) and UMASK.
960 read_etc_default_login(char ***env
, u_int
*envsize
, uid_t uid
)
962 char **tmpenv
= NULL
, *var
;
963 u_int i
, tmpenvsize
= 0;
967 * We don't want to copy the whole file to the child's environment,
968 * so we use a temporary environment and copy the variables we're
971 read_environment_file(&tmpenv
, &tmpenvsize
, "/etc/default/login");
977 var
= child_get_env(tmpenv
, "SUPATH");
979 var
= child_get_env(tmpenv
, "PATH");
981 child_set_env(env
, envsize
, "PATH", var
);
983 if ((var
= child_get_env(tmpenv
, "UMASK")) != NULL
)
984 if (sscanf(var
, "%5lo", &mask
) == 1)
987 for (i
= 0; tmpenv
[i
] != NULL
; i
++)
991 #endif /* HAVE_ETC_DEFAULT_LOGIN */
994 copy_environment(char **source
, char ***env
, u_int
*envsize
)
996 char *var_name
, *var_val
;
1002 for(i
= 0; source
[i
] != NULL
; i
++) {
1003 var_name
= xstrdup(source
[i
]);
1004 if ((var_val
= strstr(var_name
, "=")) == NULL
) {
1010 debug3("Copy environment: %s=%s", var_name
, var_val
);
1011 child_set_env(env
, envsize
, var_name
, var_val
);
1018 do_setup_env(Session
*s
, const char *shell
)
1023 struct passwd
*pw
= s
->pw
;
1024 #ifndef HAVE_LOGIN_CAP
1027 extern char **environ
;
1031 /* Initialize the environment. */
1033 env
= xcalloc(envsize
, sizeof(char *));
1038 * The Windows environment contains some setting which are
1039 * important for a running system. They must not be dropped.
1044 p
= fetch_windows_environment();
1045 copy_environment(p
, &env
, &envsize
);
1046 free_windows_environment(p
);
1051 child_set_env(&env
, &envsize
, "TZ", getenv("TZ"));
1054 /* Allow any GSSAPI methods that we've used to alter
1055 * the childs environment as they see fit
1057 ssh_gssapi_do_child(&env
, &envsize
);
1060 if (!options
.use_login
) {
1061 /* Set basic environment. */
1062 for (i
= 0; i
< s
->num_env
; i
++)
1063 child_set_env(&env
, &envsize
, s
->env
[i
].name
,
1066 child_set_env(&env
, &envsize
, "USER", pw
->pw_name
);
1067 child_set_env(&env
, &envsize
, "LOGNAME", pw
->pw_name
);
1069 child_set_env(&env
, &envsize
, "LOGIN", pw
->pw_name
);
1071 child_set_env(&env
, &envsize
, "HOME", pw
->pw_dir
);
1072 snprintf(buf
, sizeof buf
, "%.200s/%.50s",
1073 _PATH_MAILDIR
, pw
->pw_name
);
1074 child_set_env(&env
, &envsize
, "MAIL", buf
);
1075 #ifdef HAVE_LOGIN_CAP
1076 child_set_env(&env
, &envsize
, "PATH", _PATH_STDPATH
);
1077 child_set_env(&env
, &envsize
, "TERM", "su");
1079 environ
= xmalloc(sizeof(char *));
1081 (void) setusercontext(lc
, pw
, pw
->pw_uid
,
1082 LOGIN_SETENV
|LOGIN_SETPATH
);
1083 copy_environment(environ
, &env
, &envsize
);
1084 for (var
= environ
; *var
!= NULL
; ++var
)
1088 #else /* HAVE_LOGIN_CAP */
1089 # ifndef HAVE_CYGWIN
1091 * There's no standard path on Windows. The path contains
1092 * important components pointing to the system directories,
1093 * needed for loading shared libraries. So the path better
1094 * remains intact here.
1096 # ifdef HAVE_ETC_DEFAULT_LOGIN
1097 read_etc_default_login(&env
, &envsize
, pw
->pw_uid
);
1098 path
= child_get_env(env
, "PATH");
1099 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1100 if (path
== NULL
|| *path
== '\0') {
1101 child_set_env(&env
, &envsize
, "PATH",
1102 s
->pw
->pw_uid
== 0 ?
1103 SUPERUSER_PATH
: _PATH_STDPATH
);
1105 # endif /* HAVE_CYGWIN */
1106 #endif /* HAVE_LOGIN_CAP */
1108 /* Normal systems set SHELL by default. */
1109 child_set_env(&env
, &envsize
, "SHELL", shell
);
1112 /* Set custom environment options from RSA authentication. */
1113 if (!options
.use_login
) {
1114 while (custom_environment
) {
1115 struct envstring
*ce
= custom_environment
;
1118 for (i
= 0; str
[i
] != '=' && str
[i
]; i
++)
1120 if (str
[i
] == '=') {
1122 child_set_env(&env
, &envsize
, str
, str
+ i
+ 1);
1124 custom_environment
= ce
->next
;
1130 /* SSH_CLIENT deprecated */
1131 snprintf(buf
, sizeof buf
, "%.50s %d %d",
1132 get_remote_ipaddr(), get_remote_port(), get_local_port());
1133 child_set_env(&env
, &envsize
, "SSH_CLIENT", buf
);
1135 laddr
= get_local_ipaddr(packet_get_connection_in());
1136 snprintf(buf
, sizeof buf
, "%.50s %d %.50s %d",
1137 get_remote_ipaddr(), get_remote_port(), laddr
, get_local_port());
1139 child_set_env(&env
, &envsize
, "SSH_CONNECTION", buf
);
1142 child_set_env(&env
, &envsize
, "SSH_TTY", s
->tty
);
1144 child_set_env(&env
, &envsize
, "TERM", s
->term
);
1146 child_set_env(&env
, &envsize
, "DISPLAY", s
->display
);
1147 if (original_command
)
1148 child_set_env(&env
, &envsize
, "SSH_ORIGINAL_COMMAND",
1152 if (cray_tmpdir
[0] != '\0')
1153 child_set_env(&env
, &envsize
, "TMPDIR", cray_tmpdir
);
1154 #endif /* _UNICOS */
1157 * Since we clear KRB5CCNAME at startup, if it's set now then it
1158 * must have been set by a native authentication method (eg AIX or
1159 * SIA), so copy it to the child.
1164 if ((cp
= getenv("KRB5CCNAME")) != NULL
)
1165 child_set_env(&env
, &envsize
, "KRB5CCNAME", cp
);
1172 if ((cp
= getenv("AUTHSTATE")) != NULL
)
1173 child_set_env(&env
, &envsize
, "AUTHSTATE", cp
);
1174 read_environment_file(&env
, &envsize
, "/etc/environment");
1178 if (s
->authctxt
->krb5_ccname
)
1179 child_set_env(&env
, &envsize
, "KRB5CCNAME",
1180 s
->authctxt
->krb5_ccname
);
1184 * Pull in any environment variables that may have
1187 if (options
.use_pam
) {
1190 p
= fetch_pam_child_environment();
1191 copy_environment(p
, &env
, &envsize
);
1192 free_pam_environment(p
);
1194 p
= fetch_pam_environment();
1195 copy_environment(p
, &env
, &envsize
);
1196 free_pam_environment(p
);
1198 #endif /* USE_PAM */
1200 if (auth_sock_name
!= NULL
)
1201 child_set_env(&env
, &envsize
, SSH_AUTHSOCKET_ENV_NAME
,
1204 /* read $HOME/.ssh/environment. */
1205 if (options
.permit_user_env
&& !options
.use_login
) {
1206 snprintf(buf
, sizeof buf
, "%.200s/.ssh/environment",
1207 strcmp(pw
->pw_dir
, "/") ? pw
->pw_dir
: "");
1208 read_environment_file(&env
, &envsize
, buf
);
1211 /* dump the environment */
1212 fprintf(stderr
, "Environment:\n");
1213 for (i
= 0; env
[i
]; i
++)
1214 fprintf(stderr
, " %.200s\n", env
[i
]);
1220 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1221 * first in this order).
1224 do_rc_files(Session
*s
, const char *shell
)
1232 s
->display
!= NULL
&& s
->auth_proto
!= NULL
&& s
->auth_data
!= NULL
;
1234 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1235 if (!s
->is_subsystem
&& options
.adm_forced_command
== NULL
&&
1236 !no_user_rc
&& (stat(_PATH_SSH_USER_RC
, &st
) >= 0)) {
1237 snprintf(cmd
, sizeof cmd
, "%s -c '%s %s'",
1238 shell
, _PATH_BSHELL
, _PATH_SSH_USER_RC
);
1240 fprintf(stderr
, "Running %s\n", cmd
);
1241 f
= popen(cmd
, "w");
1244 fprintf(f
, "%s %s\n", s
->auth_proto
,
1248 fprintf(stderr
, "Could not run %s\n",
1250 } else if (stat(_PATH_SSH_SYSTEM_RC
, &st
) >= 0) {
1252 fprintf(stderr
, "Running %s %s\n", _PATH_BSHELL
,
1253 _PATH_SSH_SYSTEM_RC
);
1254 f
= popen(_PATH_BSHELL
" " _PATH_SSH_SYSTEM_RC
, "w");
1257 fprintf(f
, "%s %s\n", s
->auth_proto
,
1261 fprintf(stderr
, "Could not run %s\n",
1262 _PATH_SSH_SYSTEM_RC
);
1263 } else if (do_xauth
&& options
.xauth_location
!= NULL
) {
1264 /* Add authority data to .Xauthority if appropriate. */
1267 "Running %.500s remove %.100s\n",
1268 options
.xauth_location
, s
->auth_display
);
1270 "%.500s add %.100s %.100s %.100s\n",
1271 options
.xauth_location
, s
->auth_display
,
1272 s
->auth_proto
, s
->auth_data
);
1274 snprintf(cmd
, sizeof cmd
, "%s -q -",
1275 options
.xauth_location
);
1276 f
= popen(cmd
, "w");
1278 fprintf(f
, "remove %s\n",
1280 fprintf(f
, "add %s %s %s\n",
1281 s
->auth_display
, s
->auth_proto
,
1285 fprintf(stderr
, "Could not run %s\n",
1292 do_nologin(struct passwd
*pw
)
1297 #ifdef HAVE_LOGIN_CAP
1298 if (!login_getcapbool(lc
, "ignorenologin", 0) && pw
->pw_uid
)
1299 f
= fopen(login_getcapstr(lc
, "nologin", _PATH_NOLOGIN
,
1300 _PATH_NOLOGIN
), "r");
1303 f
= fopen(_PATH_NOLOGIN
, "r");
1306 /* /etc/nologin exists. Print its contents and exit. */
1307 logit("User %.100s not allowed because %s exists",
1308 pw
->pw_name
, _PATH_NOLOGIN
);
1309 while (fgets(buf
, sizeof(buf
), f
))
1318 * Chroot into a directory after checking it for safety: all path components
1319 * must be root-owned directories with strict permissions.
1322 safely_chroot(const char *path
, uid_t uid
)
1325 char component
[MAXPATHLEN
];
1329 fatal("chroot path does not begin at root");
1330 if (strlen(path
) >= sizeof(component
))
1331 fatal("chroot path too long");
1334 * Descend the path, checking that each component is a
1335 * root-owned directory with strict permissions.
1337 for (cp
= path
; cp
!= NULL
;) {
1338 if ((cp
= strchr(cp
, '/')) == NULL
)
1339 strlcpy(component
, path
, sizeof(component
));
1342 memcpy(component
, path
, cp
- path
);
1343 component
[cp
- path
] = '\0';
1346 debug3("%s: checking '%s'", __func__
, component
);
1348 if (stat(component
, &st
) != 0)
1349 fatal("%s: stat(\"%s\"): %s", __func__
,
1350 component
, strerror(errno
));
1351 if (st
.st_uid
!= 0 || (st
.st_mode
& 022) != 0)
1352 fatal("bad ownership or modes for chroot "
1353 "directory %s\"%s\"",
1354 cp
== NULL
? "" : "component ", component
);
1355 if (!S_ISDIR(st
.st_mode
))
1356 fatal("chroot path %s\"%s\" is not a directory",
1357 cp
== NULL
? "" : "component ", component
);
1361 if (chdir(path
) == -1)
1362 fatal("Unable to chdir to chroot path \"%s\": "
1363 "%s", path
, strerror(errno
));
1364 if (chroot(path
) == -1)
1365 fatal("chroot(\"%s\"): %s", path
, strerror(errno
));
1366 if (chdir("/") == -1)
1367 fatal("%s: chdir(/) after chroot: %s",
1368 __func__
, strerror(errno
));
1369 verbose("Changed root directory to \"%s\"", path
);
1372 /* Set login name, uid, gid, and groups. */
1374 do_setusercontext(struct passwd
*pw
)
1376 char *chroot_path
, *tmp
;
1379 /* Cache selinux status for later use */
1380 (void)ssh_selinux_enabled();
1384 if (getuid() == 0 || geteuid() == 0)
1385 #endif /* HAVE_CYGWIN */
1388 #ifdef HAVE_SETPCRED
1389 if (setpcred(pw
->pw_name
, (char **)NULL
) == -1)
1390 fatal("Failed to set process credentials");
1391 #endif /* HAVE_SETPCRED */
1392 #ifdef HAVE_LOGIN_CAP
1397 if (options
.use_pam
) {
1398 do_pam_setcred(use_privsep
);
1400 # endif /* USE_PAM */
1401 if (setusercontext(lc
, pw
, pw
->pw_uid
,
1402 (LOGIN_SETALL
& ~(LOGIN_SETPATH
|LOGIN_SETUSER
))) < 0) {
1403 perror("unable to set user context");
1407 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1408 /* Sets login uid for accounting */
1409 if (getluid() == -1 && setluid(pw
->pw_uid
) == -1)
1410 error("setluid: %s", strerror(errno
));
1411 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1413 if (setlogin(pw
->pw_name
) < 0)
1414 error("setlogin failed: %s", strerror(errno
));
1415 if (setgid(pw
->pw_gid
) < 0) {
1419 /* Initialize the group list. */
1420 if (initgroups(pw
->pw_name
, pw
->pw_gid
) < 0) {
1421 perror("initgroups");
1427 * PAM credentials may take the form of supplementary groups.
1428 * These will have been wiped by the above initgroups() call.
1429 * Reestablish them here.
1431 if (options
.use_pam
) {
1432 do_pam_setcred(use_privsep
);
1434 # endif /* USE_PAM */
1435 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1436 irix_setusercontext(pw
);
1437 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1442 if (set_id(pw
->pw_name
) != 0) {
1445 # endif /* USE_LIBIAF */
1448 if (options
.chroot_directory
!= NULL
&&
1449 strcasecmp(options
.chroot_directory
, "none") != 0) {
1450 tmp
= tilde_expand_filename(options
.chroot_directory
,
1452 chroot_path
= percent_expand(tmp
, "h", pw
->pw_dir
,
1453 "u", pw
->pw_name
, (char *)NULL
);
1454 safely_chroot(chroot_path
, pw
->pw_uid
);
1459 #ifdef HAVE_LOGIN_CAP
1460 if (setusercontext(lc
, pw
, pw
->pw_uid
, LOGIN_SETUSER
) < 0) {
1461 perror("unable to set user context (setuser)");
1465 /* Permanently switch to the desired uid. */
1466 permanently_set_uid(pw
);
1473 if (getuid() != pw
->pw_uid
|| geteuid() != pw
->pw_uid
)
1474 fatal("Failed to set uids to %u.", (u_int
) pw
->pw_uid
);
1477 ssh_selinux_setup_exec_context(pw
->pw_name
);
1482 do_pwchange(Session
*s
)
1485 fprintf(stderr
, "WARNING: Your password has expired.\n");
1486 if (s
->ttyfd
!= -1) {
1488 "You must change your password now and login again!\n");
1489 #ifdef PASSWD_NEEDS_USERNAME
1490 execl(_PATH_PASSWD_PROG
, "passwd", s
->pw
->pw_name
,
1493 execl(_PATH_PASSWD_PROG
, "passwd", (char *)NULL
);
1498 "Password change required but no TTY available.\n");
1504 launch_login(struct passwd
*pw
, const char *hostname
)
1506 /* Launch login(1). */
1508 execl(LOGIN_PROGRAM
, "login", "-h", hostname
,
1509 #ifdef xxxLOGIN_NEEDS_TERM
1510 (s
->term
? s
->term
: "unknown"),
1511 #endif /* LOGIN_NEEDS_TERM */
1512 #ifdef LOGIN_NO_ENDOPT
1513 "-p", "-f", pw
->pw_name
, (char *)NULL
);
1515 "-p", "-f", "--", pw
->pw_name
, (char *)NULL
);
1518 /* Login couldn't be executed, die. */
1525 child_close_fds(void)
1529 if (packet_get_connection_in() == packet_get_connection_out())
1530 close(packet_get_connection_in());
1532 close(packet_get_connection_in());
1533 close(packet_get_connection_out());
1536 * Close all descriptors related to channels. They will still remain
1537 * open in the parent.
1539 /* XXX better use close-on-exec? -markus */
1540 channel_close_all();
1543 * Close any extra file descriptors. Note that there may still be
1544 * descriptors left by system functions. They will be closed later.
1549 * Close any extra open file descriptors so that we don't have them
1550 * hanging around in clients. Note that we want to do this after
1551 * initgroups, because at least on Solaris 2.3 it leaves file
1554 for (i
= 3; i
< 64; i
++)
1559 * Performs common processing for the child, such as setting up the
1560 * environment, closing extra file descriptors, setting the user and group
1561 * ids, and executing the command or shell.
1565 do_child(Session
*s
, const char *command
)
1567 extern char **environ
;
1569 char *argv
[ARGV_MAX
];
1570 const char *shell
, *shell0
, *hostname
= NULL
;
1571 struct passwd
*pw
= s
->pw
;
1572 #ifdef HAVE_LOGIN_CAP
1576 /* remove hostkey from the child's memory */
1577 destroy_sensitive_data();
1579 /* Force a password change */
1580 if (s
->authctxt
->force_pwchange
) {
1581 do_setusercontext(pw
);
1587 /* login(1) is only called if we execute the login shell */
1588 if (options
.use_login
&& command
!= NULL
)
1589 options
.use_login
= 0;
1592 cray_setup(pw
->pw_uid
, pw
->pw_name
, command
);
1593 #endif /* _UNICOS */
1596 * Login(1) does this as well, and it needs uid 0 for the "-h"
1597 * switch, so we let login(1) to this for us.
1599 if (!options
.use_login
) {
1601 session_setup_sia(pw
, s
->ttyfd
== -1 ? NULL
: s
->tty
);
1602 if (!check_quietlogin(s
, command
))
1604 #else /* HAVE_OSF_SIA */
1605 /* When PAM is enabled we rely on it to do the nologin check */
1606 if (!options
.use_pam
)
1608 do_setusercontext(pw
);
1610 * PAM session modules in do_setusercontext may have
1611 * generated messages, so if this in an interactive
1612 * login then display them too.
1614 if (!check_quietlogin(s
, command
))
1616 #endif /* HAVE_OSF_SIA */
1620 if (options
.use_pam
&& !options
.use_login
&& !is_pam_session_open()) {
1621 debug3("PAM session not opened, exiting");
1628 * Get the shell from the password data. An empty shell field is
1629 * legal, and means /bin/sh.
1631 shell
= (pw
->pw_shell
[0] == '\0') ? _PATH_BSHELL
: pw
->pw_shell
;
1634 * Make sure $SHELL points to the shell from the password file,
1635 * even if shell is overridden from login.conf
1637 env
= do_setup_env(s
, shell
);
1639 #ifdef HAVE_LOGIN_CAP
1640 shell
= login_getcapstr(lc
, "shell", (char *)shell
, (char *)shell
);
1643 /* we have to stash the hostname before we close our socket. */
1644 if (options
.use_login
)
1645 hostname
= get_remote_name_or_ip(utmp_len
,
1648 * Close the connection descriptors; note that this is the child, and
1649 * the server will still have the socket open, and it is important
1650 * that we do not shutdown it. Note that the descriptors cannot be
1651 * closed before building the environment, as we call
1652 * get_remote_ipaddr there.
1657 * Must take new environment into use so that .ssh/rc,
1658 * /etc/ssh/sshrc and xauth are run in the proper environment.
1662 #ifdef HAVE_LOGIN_CAP
1663 lc_requirehome
= login_getcapbool(lc
, "requirehome", 0);
1666 #if defined(KRB5) && defined(USE_AFS)
1668 * At this point, we check to see if AFS is active and if we have
1669 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1670 * if we can (and need to) extend the ticket into an AFS token. If
1671 * we don't do this, we run into potential problems if the user's
1672 * home directory is in AFS and it's not world-readable.
1675 if (options
.kerberos_get_afs_token
&& k_hasafs() &&
1676 (s
->authctxt
->krb5_ctx
!= NULL
)) {
1679 debug("Getting AFS token");
1683 if (k_afs_cell_of_file(pw
->pw_dir
, cell
, sizeof(cell
)) == 0)
1684 krb5_afslog(s
->authctxt
->krb5_ctx
,
1685 s
->authctxt
->krb5_fwd_ccache
, cell
, NULL
);
1687 krb5_afslog_home(s
->authctxt
->krb5_ctx
,
1688 s
->authctxt
->krb5_fwd_ccache
, NULL
, NULL
, pw
->pw_dir
);
1692 /* Change current directory to the user's home directory. */
1693 if (chdir(pw
->pw_dir
) < 0) {
1694 fprintf(stderr
, "Could not chdir to home directory %s: %s\n",
1695 pw
->pw_dir
, strerror(errno
));
1696 #ifdef HAVE_LOGIN_CAP
1702 closefrom(STDERR_FILENO
+ 1);
1704 if (!options
.use_login
)
1705 do_rc_files(s
, shell
);
1707 /* restore SIGPIPE for child */
1708 signal(SIGPIPE
, SIG_DFL
);
1710 if (s
->is_subsystem
== SUBSYSTEM_INT_SFTP
) {
1711 extern int optind
, optreset
;
1715 setproctitle("%s@internal-sftp-server", s
->pw
->pw_name
);
1716 args
= strdup(command
? command
: "sftp-server");
1717 for (i
= 0, (p
= strtok(args
, " ")); p
; (p
= strtok(NULL
, " ")))
1718 if (i
< ARGV_MAX
- 1)
1721 optind
= optreset
= 1;
1722 __progname
= argv
[0];
1723 exit(sftp_server_main(i
, argv
, s
->pw
));
1726 if (options
.use_login
) {
1727 launch_login(pw
, hostname
);
1731 /* Get the last component of the shell name. */
1732 if ((shell0
= strrchr(shell
, '/')) != NULL
)
1738 * If we have no command, execute the shell. In this case, the shell
1739 * name to be passed in argv[0] is preceded by '-' to indicate that
1740 * this is a login shell.
1745 /* Start the shell. Set initial character to '-'. */
1748 if (strlcpy(argv0
+ 1, shell0
, sizeof(argv0
) - 1)
1749 >= sizeof(argv0
) - 1) {
1755 /* Execute the shell. */
1758 execve(shell
, argv
, env
);
1760 /* Executing the shell failed. */
1765 * Execute the command using the user's shell. This uses the -c
1766 * option to execute the command.
1768 argv
[0] = (char *) shell0
;
1770 argv
[2] = (char *) command
;
1772 execve(shell
, argv
, env
);
1781 static int did_init
= 0;
1783 debug("session_new: init");
1784 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1785 sessions
[i
].used
= 0;
1789 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1790 Session
*s
= &sessions
[i
];
1792 memset(s
, 0, sizeof(*s
));
1798 s
->x11_chanids
= NULL
;
1799 debug("session_new: session %d", i
);
1810 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1811 Session
*s
= &sessions
[i
];
1812 debug("dump: used %d session %d %p channel %d pid %ld",
1822 session_open(Authctxt
*authctxt
, int chanid
)
1824 Session
*s
= session_new();
1825 debug("session_open: channel %d", chanid
);
1827 error("no more sessions");
1830 s
->authctxt
= authctxt
;
1831 s
->pw
= authctxt
->pw
;
1832 if (s
->pw
== NULL
|| !authctxt
->valid
)
1833 fatal("no user for session %d", s
->self
);
1834 debug("session_open: session %d: link with channel %d", s
->self
, chanid
);
1840 session_by_tty(char *tty
)
1843 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1844 Session
*s
= &sessions
[i
];
1845 if (s
->used
&& s
->ttyfd
!= -1 && strcmp(s
->tty
, tty
) == 0) {
1846 debug("session_by_tty: session %d tty %s", i
, tty
);
1850 debug("session_by_tty: unknown tty %.100s", tty
);
1856 session_by_channel(int id
)
1859 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1860 Session
*s
= &sessions
[i
];
1861 if (s
->used
&& s
->chanid
== id
) {
1862 debug("session_by_channel: session %d channel %d", i
, id
);
1866 debug("session_by_channel: unknown channel %d", id
);
1872 session_by_x11_channel(int id
)
1876 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1877 Session
*s
= &sessions
[i
];
1879 if (s
->x11_chanids
== NULL
|| !s
->used
)
1881 for (j
= 0; s
->x11_chanids
[j
] != -1; j
++) {
1882 if (s
->x11_chanids
[j
] == id
) {
1883 debug("session_by_x11_channel: session %d "
1884 "channel %d", s
->self
, id
);
1889 debug("session_by_x11_channel: unknown channel %d", id
);
1895 session_by_pid(pid_t pid
)
1898 debug("session_by_pid: pid %ld", (long)pid
);
1899 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
1900 Session
*s
= &sessions
[i
];
1901 if (s
->used
&& s
->pid
== pid
)
1904 error("session_by_pid: unknown pid %ld", (long)pid
);
1910 session_window_change_req(Session
*s
)
1912 s
->col
= packet_get_int();
1913 s
->row
= packet_get_int();
1914 s
->xpixel
= packet_get_int();
1915 s
->ypixel
= packet_get_int();
1917 pty_change_window_size(s
->ptyfd
, s
->row
, s
->col
, s
->xpixel
, s
->ypixel
);
1922 session_pty_req(Session
*s
)
1928 debug("Allocating a pty not permitted for this authentication.");
1931 if (s
->ttyfd
!= -1) {
1932 packet_disconnect("Protocol error: you already have a pty.");
1936 s
->term
= packet_get_string(&len
);
1939 s
->col
= packet_get_int();
1940 s
->row
= packet_get_int();
1942 s
->row
= packet_get_int();
1943 s
->col
= packet_get_int();
1945 s
->xpixel
= packet_get_int();
1946 s
->ypixel
= packet_get_int();
1948 if (strcmp(s
->term
, "") == 0) {
1953 /* Allocate a pty and open it. */
1954 debug("Allocating pty.");
1955 if (!PRIVSEP(pty_allocate(&s
->ptyfd
, &s
->ttyfd
, s
->tty
, sizeof(s
->tty
)))) {
1961 error("session_pty_req: session %d alloc failed", s
->self
);
1964 debug("session_pty_req: session %d alloc %s", s
->self
, s
->tty
);
1966 /* for SSH1 the tty modes length is not given */
1968 n_bytes
= packet_remaining();
1969 tty_parse_modes(s
->ttyfd
, &n_bytes
);
1972 pty_setowner(s
->pw
, s
->tty
);
1974 /* Set window size from the packet. */
1975 pty_change_window_size(s
->ptyfd
, s
->row
, s
->col
, s
->xpixel
, s
->ypixel
);
1978 session_proctitle(s
);
1983 session_subsystem_req(Session
*s
)
1988 char *prog
, *cmd
, *subsys
= packet_get_string(&len
);
1992 logit("subsystem request for %.100s", subsys
);
1994 for (i
= 0; i
< options
.num_subsystems
; i
++) {
1995 if (strcmp(subsys
, options
.subsystem_name
[i
]) == 0) {
1996 prog
= options
.subsystem_command
[i
];
1997 cmd
= options
.subsystem_args
[i
];
1998 if (!strcmp(INTERNAL_SFTP_NAME
, prog
)) {
1999 s
->is_subsystem
= SUBSYSTEM_INT_SFTP
;
2000 } else if (stat(prog
, &st
) < 0) {
2001 error("subsystem: cannot stat %s: %s", prog
,
2005 s
->is_subsystem
= SUBSYSTEM_EXT
;
2007 debug("subsystem: exec() %s", cmd
);
2015 logit("subsystem request for %.100s failed, subsystem not found",
2023 session_x11_req(Session
*s
)
2027 if (s
->auth_proto
!= NULL
|| s
->auth_data
!= NULL
) {
2028 error("session_x11_req: session %d: "
2029 "x11 forwarding already active", s
->self
);
2032 s
->single_connection
= packet_get_char();
2033 s
->auth_proto
= packet_get_string(NULL
);
2034 s
->auth_data
= packet_get_string(NULL
);
2035 s
->screen
= packet_get_int();
2038 success
= session_setup_x11fwd(s
);
2040 xfree(s
->auth_proto
);
2041 xfree(s
->auth_data
);
2042 s
->auth_proto
= NULL
;
2043 s
->auth_data
= NULL
;
2049 session_shell_req(Session
*s
)
2057 session_exec_req(Session
*s
)
2060 char *command
= packet_get_string(&len
);
2062 do_exec(s
, command
);
2068 session_break_req(Session
*s
)
2071 packet_get_int(); /* ignored */
2074 if (s
->ttyfd
== -1 ||
2075 tcsendbreak(s
->ttyfd
, 0) < 0)
2081 session_env_req(Session
*s
)
2084 u_int name_len
, val_len
, i
;
2086 name
= packet_get_string(&name_len
);
2087 val
= packet_get_string(&val_len
);
2090 /* Don't set too many environment variables */
2091 if (s
->num_env
> 128) {
2092 debug2("Ignoring env request %s: too many env vars", name
);
2096 for (i
= 0; i
< options
.num_accept_env
; i
++) {
2097 if (match_pattern(name
, options
.accept_env
[i
])) {
2098 debug2("Setting env %d: %s=%s", s
->num_env
, name
, val
);
2099 s
->env
= xrealloc(s
->env
, s
->num_env
+ 1,
2101 s
->env
[s
->num_env
].name
= name
;
2102 s
->env
[s
->num_env
].val
= val
;
2107 debug2("Ignoring env request %s: disallowed name", name
);
2116 session_auth_agent_req(Session
*s
)
2118 static int called
= 0;
2120 if (no_agent_forwarding_flag
) {
2121 debug("session_auth_agent_req: no_agent_forwarding_flag");
2128 return auth_input_request_forwarding(s
->pw
);
2133 session_input_channel_req(Channel
*c
, const char *rtype
)
2138 if ((s
= session_by_channel(c
->self
)) == NULL
) {
2139 logit("session_input_channel_req: no session %d req %.100s",
2143 debug("session_input_channel_req: session %d req %s", s
->self
, rtype
);
2146 * a session is in LARVAL state until a shell, a command
2147 * or a subsystem is executed
2149 if (c
->type
== SSH_CHANNEL_LARVAL
) {
2150 if (strcmp(rtype
, "shell") == 0) {
2151 success
= session_shell_req(s
);
2152 } else if (strcmp(rtype
, "exec") == 0) {
2153 success
= session_exec_req(s
);
2154 } else if (strcmp(rtype
, "pty-req") == 0) {
2155 success
= session_pty_req(s
);
2156 } else if (strcmp(rtype
, "x11-req") == 0) {
2157 success
= session_x11_req(s
);
2158 } else if (strcmp(rtype
, "auth-agent-req@openssh.com") == 0) {
2159 success
= session_auth_agent_req(s
);
2160 } else if (strcmp(rtype
, "subsystem") == 0) {
2161 success
= session_subsystem_req(s
);
2162 } else if (strcmp(rtype
, "env") == 0) {
2163 success
= session_env_req(s
);
2166 if (strcmp(rtype
, "window-change") == 0) {
2167 success
= session_window_change_req(s
);
2168 } else if (strcmp(rtype
, "break") == 0) {
2169 success
= session_break_req(s
);
2176 session_set_fds(Session
*s
, int fdin
, int fdout
, int fderr
)
2179 fatal("session_set_fds: called for proto != 2.0");
2181 * now that have a child and a pipe to the child,
2182 * we can activate our channel and register the fd's
2184 if (s
->chanid
== -1)
2185 fatal("no channel for session %d", s
->self
);
2186 channel_set_fds(s
->chanid
,
2188 fderr
== -1 ? CHAN_EXTENDED_IGNORE
: CHAN_EXTENDED_READ
,
2190 CHAN_SES_WINDOW_DEFAULT
);
2194 * Function to perform pty cleanup. Also called if we get aborted abnormally
2195 * (e.g., due to a dropped connection).
2198 session_pty_cleanup2(Session
*s
)
2201 error("session_pty_cleanup: no session");
2207 debug("session_pty_cleanup: session %d release %s", s
->self
, s
->tty
);
2209 /* Record that the user has logged out. */
2211 record_logout(s
->pid
, s
->tty
, s
->pw
->pw_name
);
2213 /* Release the pseudo-tty. */
2215 pty_release(s
->tty
);
2218 * Close the server side of the socket pairs. We must do this after
2219 * the pty cleanup, so that another process doesn't get this pty
2220 * while we're still cleaning up.
2222 if (close(s
->ptymaster
) < 0)
2223 error("close(s->ptymaster/%d): %s", s
->ptymaster
, strerror(errno
));
2225 /* unlink pty from session */
2230 session_pty_cleanup(Session
*s
)
2232 PRIVSEP(session_pty_cleanup2(s
));
2238 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2253 return "SIG@openssh.com";
2257 session_close_x11(int id
)
2261 if ((c
= channel_by_id(id
)) == NULL
) {
2262 debug("session_close_x11: x11 channel %d missing", id
);
2264 /* Detach X11 listener */
2265 debug("session_close_x11: detach x11 channel %d", id
);
2266 channel_cancel_cleanup(id
);
2267 if (c
->ostate
!= CHAN_OUTPUT_CLOSED
)
2273 session_close_single_x11(int id
, void *arg
)
2278 debug3("session_close_single_x11: channel %d", id
);
2279 channel_cancel_cleanup(id
);
2280 if ((s
= session_by_x11_channel(id
)) == NULL
)
2281 fatal("session_close_single_x11: no x11 channel %d", id
);
2282 for (i
= 0; s
->x11_chanids
[i
] != -1; i
++) {
2283 debug("session_close_single_x11: session %d: "
2284 "closing channel %d", s
->self
, s
->x11_chanids
[i
]);
2286 * The channel "id" is already closing, but make sure we
2287 * close all of its siblings.
2289 if (s
->x11_chanids
[i
] != id
)
2290 session_close_x11(s
->x11_chanids
[i
]);
2292 xfree(s
->x11_chanids
);
2293 s
->x11_chanids
= NULL
;
2298 if (s
->auth_proto
) {
2299 xfree(s
->auth_proto
);
2300 s
->auth_proto
= NULL
;
2303 xfree(s
->auth_data
);
2304 s
->auth_data
= NULL
;
2306 if (s
->auth_display
) {
2307 xfree(s
->auth_display
);
2308 s
->auth_display
= NULL
;
2313 session_exit_message(Session
*s
, int status
)
2317 if ((c
= channel_lookup(s
->chanid
)) == NULL
)
2318 fatal("session_exit_message: session %d: no channel %d",
2319 s
->self
, s
->chanid
);
2320 debug("session_exit_message: session %d channel %d pid %ld",
2321 s
->self
, s
->chanid
, (long)s
->pid
);
2323 if (WIFEXITED(status
)) {
2324 channel_request_start(s
->chanid
, "exit-status", 0);
2325 packet_put_int(WEXITSTATUS(status
));
2327 } else if (WIFSIGNALED(status
)) {
2328 channel_request_start(s
->chanid
, "exit-signal", 0);
2329 packet_put_cstring(sig2name(WTERMSIG(status
)));
2331 packet_put_char(WCOREDUMP(status
)? 1 : 0);
2332 #else /* WCOREDUMP */
2334 #endif /* WCOREDUMP */
2335 packet_put_cstring("");
2336 packet_put_cstring("");
2339 /* Some weird exit cause. Just exit. */
2340 packet_disconnect("wait returned status %04x.", status
);
2343 /* disconnect channel */
2344 debug("session_exit_message: release channel %d", s
->chanid
);
2347 * Adjust cleanup callback attachment to send close messages when
2348 * the channel gets EOF. The session will be then be closed
2349 * by session_close_by_channel when the childs close their fds.
2351 channel_register_cleanup(c
->self
, session_close_by_channel
, 1);
2354 * emulate a write failure with 'chan_write_failed', nobody will be
2355 * interested in data we write.
2356 * Note that we must not call 'chan_read_failed', since there could
2357 * be some more data waiting in the pipe.
2359 if (c
->ostate
!= CHAN_OUTPUT_CLOSED
)
2360 chan_write_failed(c
);
2364 session_close(Session
*s
)
2368 debug("session_close: session %d pid %ld", s
->self
, (long)s
->pid
);
2370 session_pty_cleanup(s
);
2376 xfree(s
->x11_chanids
);
2377 if (s
->auth_display
)
2378 xfree(s
->auth_display
);
2380 xfree(s
->auth_data
);
2382 xfree(s
->auth_proto
);
2384 if (s
->env
!= NULL
) {
2385 for (i
= 0; i
< s
->num_env
; i
++) {
2386 xfree(s
->env
[i
].name
);
2387 xfree(s
->env
[i
].val
);
2391 session_proctitle(s
);
2395 session_close_by_pid(pid_t pid
, int status
)
2397 Session
*s
= session_by_pid(pid
);
2399 debug("session_close_by_pid: no session for pid %ld",
2403 if (s
->chanid
!= -1)
2404 session_exit_message(s
, status
);
2406 session_pty_cleanup(s
);
2411 * this is called when a channel dies before
2412 * the session 'child' itself dies
2415 session_close_by_channel(int id
, void *arg
)
2417 Session
*s
= session_by_channel(id
);
2421 debug("session_close_by_channel: no session for id %d", id
);
2424 debug("session_close_by_channel: channel %d child %ld",
2427 debug("session_close_by_channel: channel %d: has child", id
);
2429 * delay detach of session, but release pty, since
2430 * the fd's to the child are already closed
2433 session_pty_cleanup(s
);
2436 /* detach by removing callback */
2437 channel_cancel_cleanup(s
->chanid
);
2439 /* Close any X11 listeners associated with this session */
2440 if (s
->x11_chanids
!= NULL
) {
2441 for (i
= 0; s
->x11_chanids
[i
] != -1; i
++) {
2442 session_close_x11(s
->x11_chanids
[i
]);
2443 s
->x11_chanids
[i
] = -1;
2452 session_destroy_all(void (*closefunc
)(Session
*))
2455 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
2456 Session
*s
= &sessions
[i
];
2458 if (closefunc
!= NULL
)
2467 session_tty_list(void)
2469 static char buf
[1024];
2474 for (i
= 0; i
< MAX_SESSIONS
; i
++) {
2475 Session
*s
= &sessions
[i
];
2476 if (s
->used
&& s
->ttyfd
!= -1) {
2478 if (strncmp(s
->tty
, "/dev/", 5) != 0) {
2479 cp
= strrchr(s
->tty
, '/');
2480 cp
= (cp
== NULL
) ? s
->tty
: cp
+ 1;
2485 strlcat(buf
, ",", sizeof buf
);
2486 strlcat(buf
, cp
, sizeof buf
);
2490 strlcpy(buf
, "notty", sizeof buf
);
2495 session_proctitle(Session
*s
)
2498 error("no user for session %d", s
->self
);
2500 setproctitle("%s@%s", s
->pw
->pw_name
, session_tty_list());
2504 session_setup_x11fwd(Session
*s
)
2507 char display
[512], auth_display
[512];
2508 char hostname
[MAXHOSTNAMELEN
];
2511 if (no_x11_forwarding_flag
) {
2512 packet_send_debug("X11 forwarding disabled in user configuration file.");
2515 if (!options
.x11_forwarding
) {
2516 debug("X11 forwarding disabled in server configuration file.");
2519 if (!options
.xauth_location
||
2520 (stat(options
.xauth_location
, &st
) == -1)) {
2521 packet_send_debug("No xauth program; cannot forward with spoofing.");
2524 if (options
.use_login
) {
2525 packet_send_debug("X11 forwarding disabled; "
2526 "not compatible with UseLogin=yes.");
2529 if (s
->display
!= NULL
) {
2530 debug("X11 display already set.");
2533 if (x11_create_display_inet(options
.x11_display_offset
,
2534 options
.x11_use_localhost
, s
->single_connection
,
2535 &s
->display_number
, &s
->x11_chanids
) == -1) {
2536 debug("x11_create_display_inet failed.");
2539 for (i
= 0; s
->x11_chanids
[i
] != -1; i
++) {
2540 channel_register_cleanup(s
->x11_chanids
[i
],
2541 session_close_single_x11
, 0);
2544 /* Set up a suitable value for the DISPLAY variable. */
2545 if (gethostname(hostname
, sizeof(hostname
)) < 0)
2546 fatal("gethostname: %.100s", strerror(errno
));
2548 * auth_display must be used as the displayname when the
2549 * authorization entry is added with xauth(1). This will be
2550 * different than the DISPLAY string for localhost displays.
2552 if (options
.x11_use_localhost
) {
2553 snprintf(display
, sizeof display
, "localhost:%u.%u",
2554 s
->display_number
, s
->screen
);
2555 snprintf(auth_display
, sizeof auth_display
, "unix:%u.%u",
2556 s
->display_number
, s
->screen
);
2557 s
->display
= xstrdup(display
);
2558 s
->auth_display
= xstrdup(auth_display
);
2560 #ifdef IPADDR_IN_DISPLAY
2562 struct in_addr my_addr
;
2564 he
= gethostbyname(hostname
);
2566 error("Can't get IP address for X11 DISPLAY.");
2567 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2570 memcpy(&my_addr
, he
->h_addr_list
[0], sizeof(struct in_addr
));
2571 snprintf(display
, sizeof display
, "%.50s:%u.%u", inet_ntoa(my_addr
),
2572 s
->display_number
, s
->screen
);
2574 snprintf(display
, sizeof display
, "%.400s:%u.%u", hostname
,
2575 s
->display_number
, s
->screen
);
2577 s
->display
= xstrdup(display
);
2578 s
->auth_display
= xstrdup(display
);
2585 do_authenticated2(Authctxt
*authctxt
)
2587 server_loop2(authctxt
);
2591 do_cleanup(Authctxt
*authctxt
)
2593 static int called
= 0;
2595 debug("do_cleanup");
2597 /* no cleanup if we're in the child for login shell */
2601 /* avoid double cleanup */
2606 if (authctxt
== NULL
)
2610 if (options
.use_pam
) {
2612 sshpam_thread_cleanup();
2616 if (!authctxt
->authenticated
)
2620 if (options
.kerberos_ticket_cleanup
&&
2622 krb5_cleanup_proc(authctxt
);
2626 if (compat20
&& options
.gss_cleanup_creds
)
2627 ssh_gssapi_cleanup_creds();
2630 /* remove agent socket */
2631 auth_sock_cleanup_proc(authctxt
->pw
);
2634 * Cleanup ptys/utmp only if privsep is disabled,
2635 * or if running in monitor.
2637 if (!use_privsep
|| mm_is_monitor())
2638 session_destroy_all(session_pty_cleanup2
);