1 /* $NetBSD: session.c,v 1.1.1.2 2009/12/27 01:07:06 christos Exp $ */
2 /* $OpenBSD: session.c,v 1.246 2009/04/17 19:23:06 stevesk Exp $ */
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * As far as I am concerned, the code I have written for this software
8 * can be used freely for any purpose. Any derived versions of this
9 * software must be clearly marked as such, and if the derived work is
10 * incompatible with the protocol description in the RFC file, it must be
11 * called by a name other than "ssh" or "Secure Shell".
13 * SSH2 support by Markus Friedl.
14 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
25 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 __RCSID("$NetBSD: session.c,v 1.2 2009/06/07 22:38:47 christos Exp $");
39 #include <sys/types.h>
43 #include <sys/socket.h>
44 #include <sys/param.h>
45 #include <sys/queue.h>
49 #include <login_cap.h>
74 #include "auth-options.h"
75 #include "pathnames.h"
79 #include "serverloop.h"
86 #include "monitor_wrap.h"
93 #define IS_INTERNAL_SFTP(c) \
94 (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
95 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
96 c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
97 c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
101 Session
*session_new(void);
102 void session_set_fds(Session
*, int, int, int, int);
103 void session_pty_cleanup(Session
*);
104 void session_proctitle(Session
*);
105 int session_setup_x11fwd(Session
*);
106 int do_exec_pty(Session
*, const char *);
107 int do_exec_no_pty(Session
*, const char *);
108 int do_exec(Session
*, const char *);
109 void do_login(Session
*, const char *);
110 void do_child(Session
*, const char *);
112 int check_quietlogin(Session
*, const char *);
114 static void do_authenticated1(Authctxt
*);
115 static void do_authenticated2(Authctxt
*);
117 static int session_pty_req(Session
*);
120 extern ServerOptions options
;
121 extern char *__progname
;
122 extern int log_stderr
;
123 extern int debug_flag
;
124 extern u_int utmp_len
;
125 extern int startup_pipe
;
126 extern void destroy_sensitive_data(void);
127 extern Buffer loginmsg
;
129 /* original command from peer. */
130 const char *original_command
= NULL
;
133 static int sessions_first_unused
= -1;
134 static int sessions_nalloc
= 0;
135 static Session
*sessions
= NULL
;
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_dir
= xstrdup("/tmp/ssh-XXXXXXXXXX");
183 /* Create private directory for socket */
184 if (mkdtemp(auth_sock_dir
) == NULL
) {
185 packet_send_debug("Agent forwarding disabled: "
186 "mkdtemp() failed: %.100s", strerror(errno
));
188 xfree(auth_sock_dir
);
189 auth_sock_dir
= NULL
;
193 xasprintf(&auth_sock_name
, "%s/agent.%ld",
194 auth_sock_dir
, (long) getpid());
196 /* Create the socket. */
197 sock
= socket(AF_UNIX
, SOCK_STREAM
, 0);
199 error("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 error("bind: %.100s", strerror(errno
));
215 /* Restore the privileged uid. */
218 /* Start listening on the socket. */
219 if (listen(sock
, SSH_LISTEN_BACKLOG
) < 0) {
220 error("listen: %.100s", strerror(errno
));
224 /* Allocate a channel for the authentication agent socket. */
225 /* this shouldn't matter if its hpn or not - cjr */
226 nc
= channel_new("auth socket",
227 SSH_CHANNEL_AUTH_SOCKET
, sock
, sock
, -1,
228 CHAN_X11_WINDOW_DEFAULT
, CHAN_X11_PACKET_DEFAULT
,
229 0, "auth socket", 1);
230 nc
->path
= xstrdup(auth_sock_name
);
234 if (auth_sock_name
!= NULL
)
235 xfree(auth_sock_name
);
236 if (auth_sock_dir
!= NULL
) {
237 rmdir(auth_sock_dir
);
238 xfree(auth_sock_dir
);
242 auth_sock_name
= NULL
;
243 auth_sock_dir
= NULL
;
248 display_loginmsg(void)
250 if (buffer_len(&loginmsg
) > 0) {
251 buffer_append(&loginmsg
, "\0", 1);
252 printf("%s", (char *)buffer_ptr(&loginmsg
));
253 buffer_clear(&loginmsg
);
258 do_authenticated(Authctxt
*authctxt
)
260 setproctitle("%s", authctxt
->pw
->pw_name
);
262 /* setup the channel layer */
263 if (!no_port_forwarding_flag
&& options
.allow_tcp_forwarding
)
264 channel_permit_all_opens();
267 do_authenticated2(authctxt
);
269 do_authenticated1(authctxt
);
271 do_cleanup(authctxt
);
275 * Prepares for an interactive session. This is called after the user has
276 * been successfully authenticated. During this message exchange, pseudo
277 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
278 * are requested, etc.
281 do_authenticated1(Authctxt
*authctxt
)
285 int success
, type
, screen_flag
;
286 int enable_compression_after_reply
= 0;
287 u_int proto_len
, data_len
, dlen
, compression_level
= 0;
291 error("no more sessions");
294 s
->authctxt
= authctxt
;
295 s
->pw
= authctxt
->pw
;
298 * We stay in this loop until the client requests to execute a shell
304 /* Get a packet from the client. */
305 type
= packet_read();
307 /* Process the packet. */
309 case SSH_CMSG_REQUEST_COMPRESSION
:
310 compression_level
= packet_get_int();
312 if (compression_level
< 1 || compression_level
> 9) {
313 packet_send_debug("Received invalid compression level %d.",
317 if (options
.compression
== COMP_NONE
) {
318 debug2("compression disabled");
321 /* Enable compression after we have responded with SUCCESS. */
322 enable_compression_after_reply
= 1;
326 case SSH_CMSG_REQUEST_PTY
:
327 success
= session_pty_req(s
);
330 case SSH_CMSG_X11_REQUEST_FORWARDING
:
331 s
->auth_proto
= packet_get_string(&proto_len
);
332 s
->auth_data
= packet_get_string(&data_len
);
334 screen_flag
= packet_get_protocol_flags() &
335 SSH_PROTOFLAG_SCREEN_NUMBER
;
336 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag
);
338 if (packet_remaining() == 4) {
340 debug2("Buggy client: "
341 "X11 screen flag missing");
342 s
->screen
= packet_get_int();
347 success
= session_setup_x11fwd(s
);
349 xfree(s
->auth_proto
);
351 s
->auth_proto
= NULL
;
356 case SSH_CMSG_AGENT_REQUEST_FORWARDING
:
357 if (!options
.allow_agent_forwarding
||
358 no_agent_forwarding_flag
|| compat13
) {
359 debug("Authentication agent forwarding not permitted for this authentication.");
362 debug("Received authentication agent forwarding request.");
363 success
= auth_input_request_forwarding(s
->pw
);
366 case SSH_CMSG_PORT_FORWARD_REQUEST
:
367 if (no_port_forwarding_flag
) {
368 debug("Port forwarding not permitted for this authentication.");
371 if (!options
.allow_tcp_forwarding
) {
372 debug("Port forwarding not permitted.");
375 debug("Received TCP/IP port forwarding request.");
376 if (channel_input_port_forward_request(s
->pw
->pw_uid
== 0,
377 options
.gateway_ports
) < 0) {
378 debug("Port forwarding failed.");
384 case SSH_CMSG_MAX_PACKET_SIZE
:
385 if (packet_set_maxsize(packet_get_int()) > 0)
389 #if defined(AFS) || defined(KRB5)
390 case SSH_CMSG_HAVE_KERBEROS_TGT
:
391 if (!options
.kerberos_tgt_passing
) {
392 verbose("Kerberos TGT passing disabled.");
394 char *kdata
= packet_get_string(&dlen
);
397 /* XXX - 0x41, see creds_to_radix version */
398 if (kdata
[0] != 0x41) {
404 if (auth_krb5_tgt(s
->authctxt
, &tgt
))
407 verbose("Kerberos v5 TGT refused for %.100s", s
->authctxt
->user
);
411 if (auth_krb4_tgt(s
->authctxt
, kdata
))
414 verbose("Kerberos v4 TGT refused for %.100s", s
->authctxt
->user
);
420 #endif /* AFS || KRB5 */
423 case SSH_CMSG_HAVE_AFS_TOKEN
:
424 if (!options
.afs_token_passing
|| !k_hasafs()) {
425 verbose("AFS token passing disabled.");
427 /* Accept AFS token. */
428 char *token
= packet_get_string(&dlen
);
431 if (auth_afs_token(s
->authctxt
, token
))
434 verbose("AFS token refused for %.100s",
441 case SSH_CMSG_EXEC_SHELL
:
442 case SSH_CMSG_EXEC_CMD
:
443 if (type
== SSH_CMSG_EXEC_CMD
) {
444 command
= packet_get_string(&dlen
);
445 debug("Exec command '%.500s'", command
);
446 if (do_exec(s
, command
) != 0)
448 "command execution failed");
451 if (do_exec(s
, NULL
) != 0)
453 "shell execution failed");
461 * Any unknown messages in this phase are ignored,
462 * and a failure message is returned.
464 logit("Unknown packet type received after authentication: %d", type
);
466 packet_start(success
? SSH_SMSG_SUCCESS
: SSH_SMSG_FAILURE
);
470 /* Enable compression now that we have replied if appropriate. */
471 if (enable_compression_after_reply
) {
472 enable_compression_after_reply
= 0;
473 packet_start_compression(compression_level
);
480 * This is called to fork and execute a command when we have no tty. This
481 * will call do_child from the child, and server_loop from the parent after
482 * setting up file descriptors and such.
485 do_exec_no_pty(Session
*s
, const char *command
)
489 int pin
[2], pout
[2], perr
[2];
491 /* Allocate pipes for communicating with the program. */
493 error("%s: pipe in: %.100s", __func__
, strerror(errno
));
496 if (pipe(pout
) < 0) {
497 error("%s: pipe out: %.100s", __func__
, strerror(errno
));
502 if (pipe(perr
) < 0) {
503 error("%s: pipe err: %.100s", __func__
, strerror(errno
));
511 int inout
[2], err
[2];
513 /* Uses socket pairs to communicate with the program. */
514 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, inout
) < 0) {
515 error("%s: socketpair #1: %.100s", __func__
, strerror(errno
));
518 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, err
) < 0) {
519 error("%s: socketpair #2: %.100s", __func__
, strerror(errno
));
527 fatal("do_exec_no_pty: no session");
529 session_proctitle(s
);
533 if (options
.use_pam
&& !use_privsep
)
538 /* Fork the child. */
539 switch ((pid
= fork())) {
541 error("%s: fork: %.100s", __func__
, strerror(errno
));
559 /* Child. Reinitialize the log since the pid has changed. */
560 log_init(__progname
, options
.log_level
,
561 options
.log_facility
, log_stderr
);
564 * Create a new session and process group since the 4.4BSD
565 * setlogin() affects the entire process group.
568 error("setsid failed: %.100s", strerror(errno
));
572 * Redirect stdin. We close the parent side of the socket
573 * pair, and make the child side the standard input.
576 if (dup2(pin
[0], 0) < 0)
577 perror("dup2 stdin");
580 /* Redirect stdout. */
582 if (dup2(pout
[1], 1) < 0)
583 perror("dup2 stdout");
586 /* Redirect stderr. */
588 if (dup2(perr
[1], 2) < 0)
589 perror("dup2 stderr");
593 * Redirect stdin, stdout, and stderr. Stdin and stdout will
594 * use the same socket, as some programs (particularly rdist)
595 * seem to depend on it.
599 if (dup2(inout
[0], 0) < 0) /* stdin */
600 perror("dup2 stdin");
601 if (dup2(inout
[0], 1) < 0) /* stdout (same as stdin) */
602 perror("dup2 stdout");
604 if (dup2(err
[0], 2) < 0) /* stderr */
605 perror("dup2 stderr");
609 /* Do processing for the child (exec command etc). */
610 do_child(s
, command
);
617 /* Set interactive/non-interactive mode. */
618 packet_set_interactive(s
->display
!= NULL
);
621 /* We are the parent. Close the child sides of the pipes. */
627 if (s
->is_subsystem
) {
631 session_set_fds(s
, pin
[1], pout
[0], perr
[0], 0);
633 /* Enter the interactive session. */
634 server_loop(pid
, pin
[1], pout
[0], perr
[0]);
635 /* server_loop has closed pin[1], pout[0], and perr[0]. */
638 /* We are the parent. Close the child sides of the socket pairs. */
643 * Enter the interactive session. Note: server_loop must be able to
644 * handle the case that fdin and fdout are the same.
647 session_set_fds(s
, inout
[1], inout
[1],
648 s
->is_subsystem
? -1 : err
[1], 0);
652 server_loop(pid
, inout
[1], inout
[1], err
[1]);
653 /* server_loop has closed inout[1] and err[1]. */
660 * This is called to fork and execute a command when we have a tty. This
661 * will call do_child from the child, and server_loop from the parent after
662 * setting up file descriptors, controlling tty, updating wtmp, utmp,
663 * lastlog, and other such operations.
666 do_exec_pty(Session
*s
, const char *command
)
668 int fdout
, ptyfd
, ttyfd
, ptymaster
;
672 fatal("do_exec_pty: no session");
677 if (options
.use_pam
) {
678 do_pam_set_tty(s
->tty
);
685 * Create another descriptor of the pty master side for use as the
686 * standard input. We could use the original descriptor, but this
687 * simplifies code in server_loop. The descriptor is bidirectional.
688 * Do this before forking (and cleanup in the child) so as to
689 * detect and gracefully fail out-of-fd conditions.
691 if ((fdout
= dup(ptyfd
)) < 0) {
692 error("%s: dup #1: %s", __func__
, strerror(errno
));
697 /* we keep a reference to the pty master */
698 if ((ptymaster
= dup(ptyfd
)) < 0) {
699 error("%s: dup #2: %s", __func__
, strerror(errno
));
706 /* Fork the child. */
707 switch ((pid
= fork())) {
709 error("%s: fork: %.100s", __func__
, strerror(errno
));
721 /* Child. Reinitialize the log because the pid has changed. */
722 log_init(__progname
, options
.log_level
,
723 options
.log_facility
, log_stderr
);
724 /* Close the master side of the pseudo tty. */
727 /* Make the pseudo tty our controlling tty. */
728 pty_make_controlling_tty(&ttyfd
, s
->tty
);
730 /* Redirect stdin/stdout/stderr from the pseudo tty. */
731 if (dup2(ttyfd
, 0) < 0)
732 error("dup2 stdin: %s", strerror(errno
));
733 if (dup2(ttyfd
, 1) < 0)
734 error("dup2 stdout: %s", strerror(errno
));
735 if (dup2(ttyfd
, 2) < 0)
736 error("dup2 stderr: %s", strerror(errno
));
738 /* Close the extra descriptor for the pseudo tty. */
741 /* record login, etc. similar to login(1) */
742 if (!(options
.use_login
&& command
== NULL
))
743 do_login(s
, command
);
746 * Do common processing for the child, such as execing
749 do_child(s
, command
);
756 /* Parent. Close the slave side of the pseudo tty. */
759 /* Enter interactive session. */
760 s
->ptymaster
= ptymaster
;
761 packet_set_interactive(1);
763 session_set_fds(s
, ptyfd
, fdout
, -1, 1);
765 server_loop(pid
, ptyfd
, fdout
, -1);
766 /* server_loop _has_ closed ptyfd and fdout. */
772 * This is called to fork and execute a command. If another command is
773 * to be forced, execute that instead.
776 do_exec(Session
*s
, const char *command
)
780 if (options
.adm_forced_command
) {
781 original_command
= command
;
782 command
= options
.adm_forced_command
;
783 if (IS_INTERNAL_SFTP(command
))
784 s
->is_subsystem
= SUBSYSTEM_INT_SFTP
;
785 else if (s
->is_subsystem
)
786 s
->is_subsystem
= SUBSYSTEM_EXT
;
787 debug("Forced command (config) '%.900s'", command
);
788 } else if (forced_command
) {
789 original_command
= command
;
790 command
= forced_command
;
791 if (IS_INTERNAL_SFTP(command
))
792 s
->is_subsystem
= SUBSYSTEM_INT_SFTP
;
793 else if (s
->is_subsystem
)
794 s
->is_subsystem
= SUBSYSTEM_EXT
;
795 debug("Forced command (key option) '%.900s'", command
);
799 if (options
.gss_authentication
) {
800 temporarily_use_uid(s
->pw
);
801 ssh_gssapi_storecreds();
806 ret
= do_exec_pty(s
, command
);
808 ret
= do_exec_no_pty(s
, command
);
810 original_command
= NULL
;
813 * Clear loginmsg: it's the child's responsibility to display
814 * it to the user, otherwise multiple sessions may accumulate
815 * multiple copies of the login messages.
817 buffer_clear(&loginmsg
);
823 /* administrative, login(1)-like work */
825 do_login(Session
*s
, const char *command
)
828 struct sockaddr_storage from
;
829 struct passwd
* pw
= s
->pw
;
830 pid_t pid
= getpid();
833 * Get IP address of client. If the connection is not a socket, let
834 * the address be 0.0.0.0.
836 memset(&from
, 0, sizeof(from
));
837 fromlen
= sizeof(from
);
838 if (packet_connection_is_on_socket()) {
839 if (getpeername(packet_get_connection_in(),
840 (struct sockaddr
*)&from
, &fromlen
) < 0) {
841 debug("getpeername: %.100s", strerror(errno
));
846 /* Record that there was a login on that tty from the remote host. */
848 record_login(pid
, s
->tty
, pw
->pw_name
, pw
->pw_uid
,
849 get_remote_name_or_ip(utmp_len
,
851 (struct sockaddr
*)&from
, fromlen
);
855 * If password change is needed, do it now.
856 * This needs to occur before the ~/.hushlogin check.
858 if (options
.use_pam
&& !use_privsep
&& s
->authctxt
->force_pwchange
) {
861 s
->authctxt
->force_pwchange
= 0;
862 /* XXX - signal [net] parent to enable forwardings */
866 if (check_quietlogin(s
, command
))
875 * Display the message of the day.
883 if (options
.print_motd
) {
884 #ifdef HAVE_LOGIN_CAP
885 f
= fopen(login_getcapstr(lc
, "welcome", "/etc/motd",
888 f
= fopen("/etc/motd", "r");
891 while (fgets(buf
, sizeof(buf
), f
))
900 * Check for quiet login, either .hushlogin or command given.
903 check_quietlogin(Session
*s
, const char *command
)
906 struct passwd
*pw
= s
->pw
;
909 /* Return 1 if .hushlogin exists or a command given. */
912 snprintf(buf
, sizeof(buf
), "%.200s/.hushlogin", pw
->pw_dir
);
913 #ifdef HAVE_LOGIN_CAP
914 if (login_getcapbool(lc
, "hushlogin", 0) || stat(buf
, &st
) >= 0)
917 if (stat(buf
, &st
) >= 0)
924 * Sets the value of the given variable in the environment. If the variable
925 * already exists, its value is overridden.
928 child_set_env(char ***envp
, u_int
*envsizep
, const char *name
,
936 * Find the slot where the value should be stored. If the variable
937 * already exists, we reuse the slot; otherwise we append a new slot
938 * at the end of the array, expanding if necessary.
941 namelen
= strlen(name
);
942 for (i
= 0; env
[i
]; i
++)
943 if (strncmp(env
[i
], name
, namelen
) == 0 && env
[i
][namelen
] == '=')
946 /* Reuse the slot. */
949 /* New variable. Expand if necessary. */
951 if (i
>= envsize
- 1) {
953 fatal("child_set_env: too many env vars");
955 env
= (*envp
) = xrealloc(env
, envsize
, sizeof(char *));
958 /* Need to set the NULL pointer at end of array beyond the new slot. */
962 /* Allocate space and format the variable in the appropriate slot. */
963 env
[i
] = xmalloc(strlen(name
) + 1 + strlen(value
) + 1);
964 snprintf(env
[i
], strlen(name
) + 1 + strlen(value
) + 1, "%s=%s", name
, value
);
967 #ifdef HAVE_LOGIN_CAP
969 * Sets any environment variables specified in login.conf.
971 * NetBSD: login_cap.c,v 1.11 2001/07/22 13:34:01 wiz Exp
972 * Modified to use child_set_env instead of setenv.
975 lc_setuserenv(char ***env
, u_int
*envsize
, login_cap_t
*lc
)
977 const char *stop
= ", \t";
981 char *str
= login_getcapstr(lc
, "setenv", NULL
, NULL
);
983 if (str
== NULL
|| *str
== '\0')
986 /* count the sub-strings */
987 for (i
= 1, ptr
= str
; *ptr
; i
++) {
988 ptr
+= strcspn(ptr
, stop
);
993 /* allocate ptr array and string */
995 res
= malloc(count
* sizeof(char *) + strlen(str
) + 1);
1000 ptr
= (char *)res
+ count
* sizeof(char *);
1004 for (i
= 0; *ptr
&& i
< count
; i
++) {
1006 ptr
+= strcspn(ptr
, stop
);
1013 for (i
= 0; i
< count
&& res
[i
]; i
++) {
1014 if (*res
[i
] != '\0') {
1015 if ((ptr
= strchr(res
[i
], '=')) != NULL
)
1019 child_set_env(env
, envsize
, res
[i
], ptr
);
1029 * Reads environment variables from the given file and adds/overrides them
1030 * into the environment. If the file does not exist, this does nothing.
1031 * Otherwise, it must consist of empty lines, comments (line starts with '#')
1032 * and assignments of the form name=value. No other forms are allowed.
1035 read_environment_file(char ***env
, u_int
*envsize
,
1036 const char *filename
)
1043 f
= fopen(filename
, "r");
1047 while (fgets(buf
, sizeof(buf
), f
)) {
1048 if (++lineno
> 1000)
1049 fatal("Too many lines in environment file %s", filename
);
1050 for (cp
= buf
; *cp
== ' ' || *cp
== '\t'; cp
++)
1052 if (!*cp
|| *cp
== '#' || *cp
== '\n')
1055 cp
[strcspn(cp
, "\n")] = '\0';
1057 value
= strchr(cp
, '=');
1058 if (value
== NULL
) {
1059 fprintf(stderr
, "Bad line %u in %.100s\n", lineno
,
1064 * Replace the equals sign by nul, and advance value to
1069 child_set_env(env
, envsize
, cp
, value
);
1075 void copy_environment(char **, char ***, u_int
*);
1076 void copy_environment(char **source
, char ***env
, u_int
*envsize
)
1078 char *var_name
, *var_val
;
1084 for (i
= 0; source
[i
] != NULL
; i
++) {
1085 var_name
= xstrdup(source
[i
]);
1086 if ((var_val
= strstr(var_name
, "=")) == NULL
) {
1092 debug3("Copy environment: %s=%s", var_name
, var_val
);
1093 child_set_env(env
, envsize
, var_name
, var_val
);
1101 do_setup_env(Session
*s
, const char *shell
)
1106 struct passwd
*pw
= s
->pw
;
1108 /* Initialize the environment. */
1110 env
= xcalloc(envsize
, sizeof(char *));
1114 /* Allow any GSSAPI methods that we've used to alter
1115 * the childs environment as they see fit
1117 ssh_gssapi_do_child(&env
, &envsize
);
1120 if (!options
.use_login
) {
1121 #ifdef HAVE_LOGIN_CAP
1122 lc_setuserenv(&env
, &envsize
, lc
);
1124 /* Set basic environment. */
1125 for (i
= 0; i
< s
->num_env
; i
++)
1126 child_set_env(&env
, &envsize
, s
->env
[i
].name
,
1129 child_set_env(&env
, &envsize
, "USER", pw
->pw_name
);
1130 child_set_env(&env
, &envsize
, "LOGNAME", pw
->pw_name
);
1131 child_set_env(&env
, &envsize
, "HOME", pw
->pw_dir
);
1132 #ifdef HAVE_LOGIN_CAP
1133 if (setusercontext(lc
, pw
, pw
->pw_uid
, LOGIN_SETPATH
) < 0)
1134 child_set_env(&env
, &envsize
, "PATH", _PATH_STDPATH
);
1136 child_set_env(&env
, &envsize
, "PATH", getenv("PATH"));
1138 child_set_env(&env
, &envsize
, "PATH", _PATH_STDPATH
);
1141 snprintf(buf
, sizeof buf
, "%.200s/%.50s",
1142 _PATH_MAILDIR
, pw
->pw_name
);
1143 child_set_env(&env
, &envsize
, "MAIL", buf
);
1145 /* Normal systems set SHELL by default. */
1146 child_set_env(&env
, &envsize
, "SHELL", shell
);
1149 child_set_env(&env
, &envsize
, "TZ", getenv("TZ"));
1151 /* Set custom environment options from RSA authentication. */
1152 if (!options
.use_login
) {
1153 while (custom_environment
) {
1154 struct envstring
*ce
= custom_environment
;
1157 for (i
= 0; str
[i
] != '=' && str
[i
]; i
++)
1159 if (str
[i
] == '=') {
1161 child_set_env(&env
, &envsize
, str
, str
+ i
+ 1);
1163 custom_environment
= ce
->next
;
1169 /* SSH_CLIENT deprecated */
1170 snprintf(buf
, sizeof buf
, "%.50s %d %d",
1171 get_remote_ipaddr(), get_remote_port(), get_local_port());
1172 child_set_env(&env
, &envsize
, "SSH_CLIENT", buf
);
1174 laddr
= get_local_ipaddr(packet_get_connection_in());
1175 snprintf(buf
, sizeof buf
, "%.50s %d %.50s %d",
1176 get_remote_ipaddr(), get_remote_port(), laddr
, get_local_port());
1178 child_set_env(&env
, &envsize
, "SSH_CONNECTION", buf
);
1181 child_set_env(&env
, &envsize
, "SSH_TTY", s
->tty
);
1183 child_set_env(&env
, &envsize
, "TERM", s
->term
);
1185 child_set_env(&env
, &envsize
, "DISPLAY", s
->display
);
1186 if (original_command
)
1187 child_set_env(&env
, &envsize
, "SSH_ORIGINAL_COMMAND",
1190 if (s
->authctxt
->krb4_ticket_file
)
1191 child_set_env(&env
, &envsize
, "KRBTKFILE",
1192 s
->authctxt
->krb4_ticket_file
);
1195 if (s
->authctxt
->krb5_ticket_file
)
1196 child_set_env(&env
, &envsize
, "KRB5CCNAME",
1197 s
->authctxt
->krb5_ticket_file
);
1201 * Pull in any environment variables that may have
1204 if (options
.use_pam
) {
1207 p
= fetch_pam_child_environment();
1208 copy_environment(p
, &env
, &envsize
);
1209 free_pam_environment(p
);
1211 p
= fetch_pam_environment();
1212 copy_environment(p
, &env
, &envsize
);
1213 free_pam_environment(p
);
1215 #endif /* USE_PAM */
1217 if (auth_sock_name
!= NULL
)
1218 child_set_env(&env
, &envsize
, SSH_AUTHSOCKET_ENV_NAME
,
1221 /* read $HOME/.ssh/environment. */
1222 if (options
.permit_user_env
&& !options
.use_login
) {
1223 snprintf(buf
, sizeof buf
, "%.200s/.ssh/environment",
1225 read_environment_file(&env
, &envsize
, buf
);
1228 /* dump the environment */
1229 fprintf(stderr
, "Environment:\n");
1230 for (i
= 0; env
[i
]; i
++)
1231 fprintf(stderr
, " %.200s\n", env
[i
]);
1237 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1238 * first in this order).
1241 do_rc_files(Session
*s
, const char *shell
)
1249 s
->display
!= NULL
&& s
->auth_proto
!= NULL
&& s
->auth_data
!= NULL
;
1251 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1252 if (!s
->is_subsystem
&& options
.adm_forced_command
== NULL
&&
1253 !no_user_rc
&& stat(_PATH_SSH_USER_RC
, &st
) >= 0) {
1254 snprintf(cmd
, sizeof cmd
, "%s -c '%s %s'",
1255 shell
, _PATH_BSHELL
, _PATH_SSH_USER_RC
);
1257 fprintf(stderr
, "Running %s\n", cmd
);
1258 f
= popen(cmd
, "w");
1261 fprintf(f
, "%s %s\n", s
->auth_proto
,
1265 fprintf(stderr
, "Could not run %s\n",
1267 } else if (stat(_PATH_SSH_SYSTEM_RC
, &st
) >= 0) {
1269 fprintf(stderr
, "Running %s %s\n", _PATH_BSHELL
,
1270 _PATH_SSH_SYSTEM_RC
);
1271 f
= popen(_PATH_BSHELL
" " _PATH_SSH_SYSTEM_RC
, "w");
1274 fprintf(f
, "%s %s\n", s
->auth_proto
,
1278 fprintf(stderr
, "Could not run %s\n",
1279 _PATH_SSH_SYSTEM_RC
);
1280 } else if (do_xauth
&& options
.xauth_location
!= NULL
) {
1281 /* Add authority data to .Xauthority if appropriate. */
1284 "Running %.500s remove %.100s\n",
1285 options
.xauth_location
, s
->auth_display
);
1287 "%.500s add %.100s %.100s %.100s\n",
1288 options
.xauth_location
, s
->auth_display
,
1289 s
->auth_proto
, s
->auth_data
);
1291 snprintf(cmd
, sizeof cmd
, "%s -q -",
1292 options
.xauth_location
);
1293 f
= popen(cmd
, "w");
1295 fprintf(f
, "remove %s\n",
1297 fprintf(f
, "add %s %s %s\n",
1298 s
->auth_display
, s
->auth_proto
,
1302 fprintf(stderr
, "Could not run %s\n",
1309 do_nologin(struct passwd
*pw
)
1314 #ifdef HAVE_LOGIN_CAP
1315 if (!login_getcapbool(lc
, "ignorenologin", 0) && pw
->pw_uid
)
1316 f
= fopen(login_getcapstr(lc
, "nologin", _PATH_NOLOGIN
,
1317 _PATH_NOLOGIN
), "r");
1320 f
= fopen(_PATH_NOLOGIN
, "r");
1323 /* /etc/nologin exists. Print its contents and exit. */
1324 logit("User %.100s not allowed because %s exists",
1325 pw
->pw_name
, _PATH_NOLOGIN
);
1326 while (fgets(buf
, sizeof(buf
), f
))
1334 * Chroot into a directory after checking it for safety: all path components
1335 * must be root-owned directories with strict permissions.
1338 safely_chroot(const char *path
, uid_t uid
)
1341 char component
[MAXPATHLEN
];
1345 fatal("chroot path does not begin at root");
1346 if (strlen(path
) >= sizeof(component
))
1347 fatal("chroot path too long");
1350 * Descend the path, checking that each component is a
1351 * root-owned directory with strict permissions.
1353 for (cp
= path
; cp
!= NULL
;) {
1354 if ((cp
= strchr(cp
, '/')) == NULL
)
1355 strlcpy(component
, path
, sizeof(component
));
1358 memcpy(component
, path
, cp
- path
);
1359 component
[cp
- path
] = '\0';
1362 debug3("%s: checking '%s'", __func__
, component
);
1364 if (stat(component
, &st
) != 0)
1365 fatal("%s: stat(\"%s\"): %s", __func__
,
1366 component
, strerror(errno
));
1367 if (st
.st_uid
!= 0 || (st
.st_mode
& 022) != 0)
1368 fatal("bad ownership or modes for chroot "
1369 "directory %s\"%s\"",
1370 cp
== NULL
? "" : "component ", component
);
1371 if (!S_ISDIR(st
.st_mode
))
1372 fatal("chroot path %s\"%s\" is not a directory",
1373 cp
== NULL
? "" : "component ", component
);
1377 if (chdir(path
) == -1)
1378 fatal("Unable to chdir to chroot path \"%s\": "
1379 "%s", path
, strerror(errno
));
1380 if (chroot(path
) == -1)
1381 fatal("chroot(\"%s\"): %s", path
, strerror(errno
));
1382 if (chdir("/") == -1)
1383 fatal("%s: chdir(/) after chroot: %s",
1384 __func__
, strerror(errno
));
1385 verbose("Changed root directory to \"%s\"", path
);
1388 /* Set login name, uid, gid, and groups. */
1390 do_setusercontext(struct passwd
*pw
)
1392 char *chroot_path
, *tmp
;
1394 if (getuid() == 0 || geteuid() == 0) {
1395 #ifdef HAVE_LOGIN_CAP
1397 if (options
.use_pam
) {
1398 do_pam_setcred(use_privsep
);
1400 # endif /* USE_PAM */
1401 /* Prepare groups */
1402 if (setusercontext(lc
, pw
, pw
->pw_uid
,
1403 (LOGIN_SETALL
& ~(LOGIN_SETPATH
|LOGIN_SETUSER
))) < 0) {
1404 perror("unable to set user context");
1409 if (setlogin(pw
->pw_name
) < 0)
1410 error("setlogin failed: %s", strerror(errno
));
1411 if (setgid(pw
->pw_gid
) < 0) {
1415 /* Initialize the group list. */
1416 if (initgroups(pw
->pw_name
, pw
->pw_gid
) < 0) {
1417 perror("initgroups");
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
) {
1428 do_pam_setcred(use_privsep
);
1430 # endif /* USE_PAM */
1432 if (options
.chroot_directory
!= NULL
&&
1433 strcasecmp(options
.chroot_directory
, "none") != 0) {
1434 tmp
= tilde_expand_filename(options
.chroot_directory
,
1436 chroot_path
= percent_expand(tmp
, "h", pw
->pw_dir
,
1437 "u", pw
->pw_name
, (char *)NULL
);
1438 safely_chroot(chroot_path
, pw
->pw_uid
);
1443 #ifdef HAVE_LOGIN_CAP
1445 if (setusercontext(lc
, pw
, pw
->pw_uid
, LOGIN_SETUSER
) < 0) {
1446 perror("unable to set user context (setuser)");
1450 /* Permanently switch to the desired uid. */
1451 permanently_set_uid(pw
);
1454 if (getuid() != pw
->pw_uid
|| geteuid() != pw
->pw_uid
)
1455 fatal("Failed to set uids to %u.", (u_int
) pw
->pw_uid
);
1459 do_pwchange(Session
*s
)
1462 fprintf(stderr
, "WARNING: Your password has expired.\n");
1463 if (s
->ttyfd
!= -1) {
1465 "You must change your password now and login again!\n");
1466 execl(_PATH_PASSWD_PROG
, "passwd", (char *)NULL
);
1470 "Password change required but no TTY available.\n");
1476 launch_login(struct passwd
*pw
, const char *hostname
)
1478 /* Launch login(1). */
1480 execl("/usr/bin/login", "login", "-h", hostname
,
1481 "-p", "-f", "--", pw
->pw_name
, (char *)NULL
);
1483 /* Login couldn't be executed, die. */
1490 child_close_fds(void)
1494 if (packet_get_connection_in() == packet_get_connection_out())
1495 close(packet_get_connection_in());
1497 close(packet_get_connection_in());
1498 close(packet_get_connection_out());
1501 * Close all descriptors related to channels. They will still remain
1502 * open in the parent.
1504 /* XXX better use close-on-exec? -markus */
1505 channel_close_all();
1508 * Close any extra file descriptors. Note that there may still be
1509 * descriptors left by system functions. They will be closed later.
1514 * Close any extra open file descriptors so that we don't have them
1515 * hanging around in clients. Note that we want to do this after
1516 * initgroups, because at least on Solaris 2.3 it leaves file
1519 for (i
= 3; i
< 64; i
++)
1524 * Performs common processing for the child, such as setting up the
1525 * environment, closing extra file descriptors, setting the user and group
1526 * ids, and executing the command or shell.
1530 do_child(Session
*s
, const char *command
)
1532 extern char **environ
;
1534 char *argv
[ARGV_MAX
];
1535 const char *shell
, *shell0
, *hostname
= NULL
;
1536 struct passwd
*pw
= s
->pw
;
1539 /* remove hostkey from the child's memory */
1540 destroy_sensitive_data();
1542 /* Force a password change */
1543 if (s
->authctxt
->force_pwchange
) {
1544 do_setusercontext(pw
);
1550 /* login(1) is only called if we execute the login shell */
1551 if (options
.use_login
&& command
!= NULL
)
1552 options
.use_login
= 0;
1555 * Login(1) does this as well, and it needs uid 0 for the "-h"
1556 * switch, so we let login(1) to this for us.
1558 if (!options
.use_login
) {
1560 do_setusercontext(pw
);
1562 * PAM session modules in do_setusercontext may have
1563 * generated messages, so if this in an interactive
1564 * login then display them too.
1566 if (!check_quietlogin(s
, command
))
1570 if (options
.use_pam
&& !is_pam_session_open()) {
1571 debug3("PAM session not opened, exiting");
1578 * Get the shell from the password data. An empty shell field is
1579 * legal, and means /bin/sh.
1581 shell
= (pw
->pw_shell
[0] == '\0') ? _PATH_BSHELL
: pw
->pw_shell
;
1584 * Make sure $SHELL points to the shell from the password file,
1585 * even if shell is overridden from login.conf
1587 env
= do_setup_env(s
, shell
);
1589 #ifdef HAVE_LOGIN_CAP
1590 shell
= login_getcapstr(lc
, "shell", (char *)shell
, (char *)shell
);
1593 /* we have to stash the hostname before we close our socket. */
1594 if (options
.use_login
)
1595 hostname
= get_remote_name_or_ip(utmp_len
,
1598 * Close the connection descriptors; note that this is the child, and
1599 * the server will still have the socket open, and it is important
1600 * that we do not shutdown it. Note that the descriptors cannot be
1601 * closed before building the environment, as we call
1602 * get_remote_ipaddr there.
1607 * Must take new environment into use so that .ssh/rc,
1608 * /etc/ssh/sshrc and xauth are run in the proper environment.
1614 * At this point, we check to see if AFS is active and if we have
1615 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1616 * if we can (and need to) extend the ticket into an AFS token. If
1617 * we don't do this, we run into potential problems if the user's
1618 * home directory is in AFS and it's not world-readable.
1621 if (options
.kerberos_get_afs_token
&& k_hasafs() &&
1622 (s
->authctxt
->krb5_ctx
!= NULL
)) {
1625 debug("Getting AFS token");
1629 if (k_afs_cell_of_file(pw
->pw_dir
, cell
, sizeof(cell
)) == 0)
1630 krb5_afslog(s
->authctxt
->krb5_ctx
,
1631 s
->authctxt
->krb5_fwd_ccache
, cell
, NULL
);
1633 krb5_afslog_home(s
->authctxt
->krb5_ctx
,
1634 s
->authctxt
->krb5_fwd_ccache
, NULL
, NULL
, pw
->pw_dir
);
1638 /* Change current directory to the user's home directory. */
1639 if (chdir(pw
->pw_dir
) < 0) {
1640 /* Suppress missing homedir warning for chroot case */
1641 r
= login_getcapbool(lc
, "requirehome", 0);
1642 if (r
|| options
.chroot_directory
== NULL
)
1643 fprintf(stderr
, "Could not chdir to home "
1644 "directory %s: %s\n", pw
->pw_dir
,
1650 closefrom(STDERR_FILENO
+ 1);
1652 if (!options
.use_login
)
1653 do_rc_files(s
, shell
);
1655 /* restore SIGPIPE for child */
1656 signal(SIGPIPE
, SIG_DFL
);
1658 if (s
->is_subsystem
== SUBSYSTEM_INT_SFTP
) {
1659 extern int optind
, optreset
;
1663 setproctitle("%s@%s", s
->pw
->pw_name
, INTERNAL_SFTP_NAME
);
1664 args
= xstrdup(command
? command
: "sftp-server");
1665 for (i
= 0, (p
= strtok(args
, " ")); p
; (p
= strtok(NULL
, " ")))
1666 if (i
< ARGV_MAX
- 1)
1669 optind
= optreset
= 1;
1670 __progname
= argv
[0];
1671 exit(sftp_server_main(i
, argv
, s
->pw
));
1674 if (options
.use_login
) {
1675 launch_login(pw
, hostname
);
1679 /* Get the last component of the shell name. */
1680 if ((shell0
= strrchr(shell
, '/')) != NULL
)
1686 * If we have no command, execute the shell. In this case, the shell
1687 * name to be passed in argv[0] is preceded by '-' to indicate that
1688 * this is a login shell.
1693 /* Start the shell. Set initial character to '-'. */
1696 if (strlcpy(argv0
+ 1, shell0
, sizeof(argv0
) - 1)
1697 >= sizeof(argv0
) - 1) {
1703 /* Execute the shell. */
1706 execve(shell
, argv
, env
);
1708 /* Executing the shell failed. */
1713 * Execute the command using the user's shell. This uses the -c
1714 * option to execute the command.
1716 argv
[0] = (char *) shell0
;
1718 argv
[2] = (char *) command
;
1720 execve(shell
, argv
, env
);
1726 session_unused(int id
)
1728 debug3("%s: session id %d unused", __func__
, id
);
1729 if (id
>= options
.max_sessions
||
1730 id
>= sessions_nalloc
) {
1731 fatal("%s: insane session id %d (max %d nalloc %d)",
1732 __func__
, id
, options
.max_sessions
, sessions_nalloc
);
1734 bzero(&sessions
[id
], sizeof(*sessions
));
1735 sessions
[id
].self
= id
;
1736 sessions
[id
].used
= 0;
1737 sessions
[id
].chanid
= -1;
1738 sessions
[id
].ptyfd
= -1;
1739 sessions
[id
].ttyfd
= -1;
1740 sessions
[id
].ptymaster
= -1;
1741 sessions
[id
].x11_chanids
= NULL
;
1742 sessions
[id
].next_unused
= sessions_first_unused
;
1743 sessions_first_unused
= id
;
1751 if (sessions_first_unused
== -1) {
1752 if (sessions_nalloc
>= options
.max_sessions
)
1754 debug2("%s: allocate (allocated %d max %d)",
1755 __func__
, sessions_nalloc
, options
.max_sessions
);
1756 tmp
= xrealloc(sessions
, sessions_nalloc
+ 1,
1759 error("%s: cannot allocate %d sessions",
1760 __func__
, sessions_nalloc
+ 1);
1764 session_unused(sessions_nalloc
++);
1767 if (sessions_first_unused
>= sessions_nalloc
||
1768 sessions_first_unused
< 0) {
1769 fatal("%s: insane first_unused %d max %d nalloc %d",
1770 __func__
, sessions_first_unused
, options
.max_sessions
,
1774 s
= &sessions
[sessions_first_unused
];
1776 fatal("%s: session %d already used",
1777 __func__
, sessions_first_unused
);
1779 sessions_first_unused
= s
->next_unused
;
1781 s
->next_unused
= -1;
1782 debug("session_new: session %d", s
->self
);
1791 for (i
= 0; i
< sessions_nalloc
; i
++) {
1792 Session
*s
= &sessions
[i
];
1794 debug("dump: used %d next_unused %d session %d %p "
1795 "channel %d pid %ld",
1806 session_open(Authctxt
*authctxt
, int chanid
)
1808 Session
*s
= session_new();
1809 debug("session_open: channel %d", chanid
);
1811 error("no more sessions");
1814 s
->authctxt
= authctxt
;
1815 s
->pw
= authctxt
->pw
;
1816 if (s
->pw
== NULL
|| !authctxt
->valid
)
1817 fatal("no user for session %d", s
->self
);
1818 debug("session_open: session %d: link with channel %d", s
->self
, chanid
);
1824 session_by_tty(char *tty
)
1827 for (i
= 0; i
< sessions_nalloc
; i
++) {
1828 Session
*s
= &sessions
[i
];
1829 if (s
->used
&& s
->ttyfd
!= -1 && strcmp(s
->tty
, tty
) == 0) {
1830 debug("session_by_tty: session %d tty %s", i
, tty
);
1834 debug("session_by_tty: unknown tty %.100s", tty
);
1840 session_by_channel(int id
)
1843 for (i
= 0; i
< sessions_nalloc
; i
++) {
1844 Session
*s
= &sessions
[i
];
1845 if (s
->used
&& s
->chanid
== id
) {
1846 debug("session_by_channel: session %d channel %d",
1851 debug("session_by_channel: unknown channel %d", id
);
1857 session_by_x11_channel(int id
)
1861 for (i
= 0; i
< sessions_nalloc
; i
++) {
1862 Session
*s
= &sessions
[i
];
1864 if (s
->x11_chanids
== NULL
|| !s
->used
)
1866 for (j
= 0; s
->x11_chanids
[j
] != -1; j
++) {
1867 if (s
->x11_chanids
[j
] == id
) {
1868 debug("session_by_x11_channel: session %d "
1869 "channel %d", s
->self
, id
);
1874 debug("session_by_x11_channel: unknown channel %d", id
);
1880 session_by_pid(pid_t pid
)
1883 debug("session_by_pid: pid %ld", (long)pid
);
1884 for (i
= 0; i
< sessions_nalloc
; i
++) {
1885 Session
*s
= &sessions
[i
];
1886 if (s
->used
&& s
->pid
== pid
)
1889 error("session_by_pid: unknown pid %ld", (long)pid
);
1895 session_window_change_req(Session
*s
)
1897 s
->col
= packet_get_int();
1898 s
->row
= packet_get_int();
1899 s
->xpixel
= packet_get_int();
1900 s
->ypixel
= packet_get_int();
1902 pty_change_window_size(s
->ptyfd
, s
->row
, s
->col
, s
->xpixel
, s
->ypixel
);
1907 session_pty_req(Session
*s
)
1913 debug("Allocating a pty not permitted for this authentication.");
1916 if (s
->ttyfd
!= -1) {
1917 packet_disconnect("Protocol error: you already have a pty.");
1921 s
->term
= packet_get_string(&len
);
1924 s
->col
= packet_get_int();
1925 s
->row
= packet_get_int();
1927 s
->row
= packet_get_int();
1928 s
->col
= packet_get_int();
1930 s
->xpixel
= packet_get_int();
1931 s
->ypixel
= packet_get_int();
1933 if (strcmp(s
->term
, "") == 0) {
1938 /* Allocate a pty and open it. */
1939 debug("Allocating pty.");
1940 if (!PRIVSEP(pty_allocate(&s
->ptyfd
, &s
->ttyfd
, s
->tty
,
1947 error("session_pty_req: session %d alloc failed", s
->self
);
1950 debug("session_pty_req: session %d alloc %s", s
->self
, s
->tty
);
1952 /* for SSH1 the tty modes length is not given */
1954 n_bytes
= packet_remaining();
1955 tty_parse_modes(s
->ttyfd
, &n_bytes
);
1958 pty_setowner(s
->pw
, s
->tty
);
1960 /* Set window size from the packet. */
1961 pty_change_window_size(s
->ptyfd
, s
->row
, s
->col
, s
->xpixel
, s
->ypixel
);
1964 session_proctitle(s
);
1969 session_subsystem_req(Session
*s
)
1974 char *prog
, *cmd
, *subsys
= packet_get_string(&len
);
1978 logit("subsystem request for %.100s", subsys
);
1980 for (i
= 0; i
< options
.num_subsystems
; i
++) {
1981 if (strcmp(subsys
, options
.subsystem_name
[i
]) == 0) {
1982 prog
= options
.subsystem_command
[i
];
1983 cmd
= options
.subsystem_args
[i
];
1984 if (!strcmp(INTERNAL_SFTP_NAME
, prog
)) {
1985 s
->is_subsystem
= SUBSYSTEM_INT_SFTP
;
1986 } else if (stat(prog
, &st
) < 0) {
1987 error("subsystem: cannot stat %s: %s", prog
,
1991 s
->is_subsystem
= SUBSYSTEM_EXT
;
1993 debug("subsystem: exec() %s", cmd
);
1994 success
= do_exec(s
, cmd
) == 0;
2000 logit("subsystem request for %.100s failed, subsystem not found",
2008 session_x11_req(Session
*s
)
2012 if (s
->auth_proto
!= NULL
|| s
->auth_data
!= NULL
) {
2013 error("session_x11_req: session %d: "
2014 "x11 forwarding already active", s
->self
);
2017 s
->single_connection
= packet_get_char();
2018 s
->auth_proto
= packet_get_string(NULL
);
2019 s
->auth_data
= packet_get_string(NULL
);
2020 s
->screen
= packet_get_int();
2023 success
= session_setup_x11fwd(s
);
2025 xfree(s
->auth_proto
);
2026 xfree(s
->auth_data
);
2027 s
->auth_proto
= NULL
;
2028 s
->auth_data
= NULL
;
2034 session_shell_req(Session
*s
)
2037 return do_exec(s
, NULL
) == 0;
2041 session_exec_req(Session
*s
)
2045 char *command
= packet_get_string(&len
);
2047 success
= do_exec(s
, command
) == 0;
2053 session_break_req(Session
*s
)
2056 packet_get_int(); /* ignored */
2059 if (s
->ttyfd
== -1 || tcsendbreak(s
->ttyfd
, 0) < 0)
2065 session_env_req(Session
*s
)
2068 u_int name_len
, val_len
, i
;
2070 name
= packet_get_string(&name_len
);
2071 val
= packet_get_string(&val_len
);
2074 /* Don't set too many environment variables */
2075 if (s
->num_env
> 128) {
2076 debug2("Ignoring env request %s: too many env vars", name
);
2080 for (i
= 0; i
< options
.num_accept_env
; i
++) {
2081 if (match_pattern(name
, options
.accept_env
[i
])) {
2082 debug2("Setting env %d: %s=%s", s
->num_env
, name
, val
);
2083 s
->env
= xrealloc(s
->env
, s
->num_env
+ 1,
2085 s
->env
[s
->num_env
].name
= name
;
2086 s
->env
[s
->num_env
].val
= val
;
2091 debug2("Ignoring env request %s: disallowed name", name
);
2100 session_auth_agent_req(Session
*s
)
2102 static int called
= 0;
2104 if (no_agent_forwarding_flag
|| !options
.allow_agent_forwarding
) {
2105 debug("session_auth_agent_req: no_agent_forwarding_flag");
2112 return auth_input_request_forwarding(s
->pw
);
2117 session_input_channel_req(Channel
*c
, const char *rtype
)
2122 if ((s
= session_by_channel(c
->self
)) == NULL
) {
2123 logit("session_input_channel_req: no session %d req %.100s",
2127 debug("session_input_channel_req: session %d req %s", s
->self
, rtype
);
2130 * a session is in LARVAL state until a shell, a command
2131 * or a subsystem is executed
2133 if (c
->type
== SSH_CHANNEL_LARVAL
) {
2134 if (strcmp(rtype
, "shell") == 0) {
2135 success
= session_shell_req(s
);
2136 } else if (strcmp(rtype
, "exec") == 0) {
2137 success
= session_exec_req(s
);
2138 } else if (strcmp(rtype
, "pty-req") == 0) {
2139 success
= session_pty_req(s
);
2140 } else if (strcmp(rtype
, "x11-req") == 0) {
2141 success
= session_x11_req(s
);
2142 } else if (strcmp(rtype
, "auth-agent-req@openssh.com") == 0) {
2143 success
= session_auth_agent_req(s
);
2144 } else if (strcmp(rtype
, "subsystem") == 0) {
2145 success
= session_subsystem_req(s
);
2146 } else if (strcmp(rtype
, "env") == 0) {
2147 success
= session_env_req(s
);
2150 if (strcmp(rtype
, "window-change") == 0) {
2151 success
= session_window_change_req(s
);
2152 } else if (strcmp(rtype
, "break") == 0) {
2153 success
= session_break_req(s
);
2160 session_set_fds(Session
*s
, int fdin
, int fdout
, int fderr
, int is_tty
)
2163 fatal("session_set_fds: called for proto != 2.0");
2165 * now that have a child and a pipe to the child,
2166 * we can activate our channel and register the fd's
2168 if (s
->chanid
== -1)
2169 fatal("no channel for session %d", s
->self
);
2170 if(options
.hpn_disabled
)
2171 channel_set_fds(s
->chanid
,
2173 fderr
== -1 ? CHAN_EXTENDED_IGNORE
: CHAN_EXTENDED_READ
,
2174 1, is_tty
, CHAN_SES_WINDOW_DEFAULT
);
2176 channel_set_fds(s
->chanid
,
2178 fderr
== -1 ? CHAN_EXTENDED_IGNORE
: CHAN_EXTENDED_READ
,
2179 1, is_tty
, options
.hpn_buffer_size
);
2183 * Function to perform pty cleanup. Also called if we get aborted abnormally
2184 * (e.g., due to a dropped connection).
2187 session_pty_cleanup2(Session
*s
)
2190 error("session_pty_cleanup: no session");
2196 debug("session_pty_cleanup: session %d release %s", s
->self
, s
->tty
);
2198 /* Record that the user has logged out. */
2200 record_logout(s
->pid
, s
->tty
);
2202 /* Release the pseudo-tty. */
2204 pty_release(s
->tty
);
2207 * Close the server side of the socket pairs. We must do this after
2208 * the pty cleanup, so that another process doesn't get this pty
2209 * while we're still cleaning up.
2211 if (s
->ptymaster
!= -1 && close(s
->ptymaster
) < 0)
2212 error("close(s->ptymaster/%d): %s",
2213 s
->ptymaster
, strerror(errno
));
2215 /* unlink pty from session */
2220 session_pty_cleanup(Session
*s
)
2222 PRIVSEP(session_pty_cleanup2(s
));
2228 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2243 return "SIG@openssh.com";
2247 session_close_x11(int id
)
2251 if ((c
= channel_by_id(id
)) == NULL
) {
2252 debug("session_close_x11: x11 channel %d missing", id
);
2254 /* Detach X11 listener */
2255 debug("session_close_x11: detach x11 channel %d", id
);
2256 channel_cancel_cleanup(id
);
2257 if (c
->ostate
!= CHAN_OUTPUT_CLOSED
)
2263 session_close_single_x11(int id
, void *arg
)
2268 debug3("session_close_single_x11: channel %d", id
);
2269 channel_cancel_cleanup(id
);
2270 if ((s
= session_by_x11_channel(id
)) == NULL
)
2271 fatal("session_close_single_x11: no x11 channel %d", id
);
2272 for (i
= 0; s
->x11_chanids
[i
] != -1; i
++) {
2273 debug("session_close_single_x11: session %d: "
2274 "closing channel %d", s
->self
, s
->x11_chanids
[i
]);
2276 * The channel "id" is already closing, but make sure we
2277 * close all of its siblings.
2279 if (s
->x11_chanids
[i
] != id
)
2280 session_close_x11(s
->x11_chanids
[i
]);
2282 xfree(s
->x11_chanids
);
2283 s
->x11_chanids
= NULL
;
2288 if (s
->auth_proto
) {
2289 xfree(s
->auth_proto
);
2290 s
->auth_proto
= NULL
;
2293 xfree(s
->auth_data
);
2294 s
->auth_data
= NULL
;
2296 if (s
->auth_display
) {
2297 xfree(s
->auth_display
);
2298 s
->auth_display
= NULL
;
2303 session_exit_message(Session
*s
, int status
)
2307 if ((c
= channel_lookup(s
->chanid
)) == NULL
)
2308 fatal("session_exit_message: session %d: no channel %d",
2309 s
->self
, s
->chanid
);
2310 debug("session_exit_message: session %d channel %d pid %ld",
2311 s
->self
, s
->chanid
, (long)s
->pid
);
2313 if (WIFEXITED(status
)) {
2314 channel_request_start(s
->chanid
, "exit-status", 0);
2315 packet_put_int(WEXITSTATUS(status
));
2317 } else if (WIFSIGNALED(status
)) {
2318 channel_request_start(s
->chanid
, "exit-signal", 0);
2319 packet_put_cstring(sig2name(WTERMSIG(status
)));
2320 packet_put_char(WCOREDUMP(status
)? 1 : 0);
2321 packet_put_cstring("");
2322 packet_put_cstring("");
2325 /* Some weird exit cause. Just exit. */
2326 packet_disconnect("wait returned status %04x.", status
);
2329 /* disconnect channel */
2330 debug("session_exit_message: release channel %d", s
->chanid
);
2333 * Adjust cleanup callback attachment to send close messages when
2334 * the channel gets EOF. The session will be then be closed
2335 * by session_close_by_channel when the childs close their fds.
2337 channel_register_cleanup(c
->self
, session_close_by_channel
, 1);
2340 * emulate a write failure with 'chan_write_failed', nobody will be
2341 * interested in data we write.
2342 * Note that we must not call 'chan_read_failed', since there could
2343 * be some more data waiting in the pipe.
2345 if (c
->ostate
!= CHAN_OUTPUT_CLOSED
)
2346 chan_write_failed(c
);
2350 session_close(Session
*s
)
2354 debug("session_close: session %d pid %ld", s
->self
, (long)s
->pid
);
2356 session_pty_cleanup(s
);
2362 xfree(s
->x11_chanids
);
2363 if (s
->auth_display
)
2364 xfree(s
->auth_display
);
2366 xfree(s
->auth_data
);
2368 xfree(s
->auth_proto
);
2369 if (s
->env
!= NULL
) {
2370 for (i
= 0; i
< s
->num_env
; i
++) {
2371 xfree(s
->env
[i
].name
);
2372 xfree(s
->env
[i
].val
);
2376 session_proctitle(s
);
2377 session_unused(s
->self
);
2381 session_close_by_pid(pid_t pid
, int status
)
2383 Session
*s
= session_by_pid(pid
);
2385 debug("session_close_by_pid: no session for pid %ld",
2389 if (s
->chanid
!= -1)
2390 session_exit_message(s
, status
);
2392 session_pty_cleanup(s
);
2397 * this is called when a channel dies before
2398 * the session 'child' itself dies
2401 session_close_by_channel(int id
, void *arg
)
2403 Session
*s
= session_by_channel(id
);
2407 debug("session_close_by_channel: no session for id %d", id
);
2410 debug("session_close_by_channel: channel %d child %ld",
2413 debug("session_close_by_channel: channel %d: has child", id
);
2415 * delay detach of session, but release pty, since
2416 * the fd's to the child are already closed
2419 session_pty_cleanup(s
);
2422 /* detach by removing callback */
2423 channel_cancel_cleanup(s
->chanid
);
2425 /* Close any X11 listeners associated with this session */
2426 if (s
->x11_chanids
!= NULL
) {
2427 for (i
= 0; s
->x11_chanids
[i
] != -1; i
++) {
2428 session_close_x11(s
->x11_chanids
[i
]);
2429 s
->x11_chanids
[i
] = -1;
2438 session_destroy_all(void (*closefunc
)(Session
*))
2441 for (i
= 0; i
< sessions_nalloc
; i
++) {
2442 Session
*s
= &sessions
[i
];
2444 if (closefunc
!= NULL
)
2453 session_tty_list(void)
2455 static char buf
[1024];
2458 for (i
= 0; i
< sessions_nalloc
; i
++) {
2459 Session
*s
= &sessions
[i
];
2460 if (s
->used
&& s
->ttyfd
!= -1) {
2463 strlcat(buf
, ",", sizeof buf
);
2464 if ((p
= strstr(s
->tty
, "/pts/")) != NULL
)
2467 if ((p
= strrchr(s
->tty
, '/')) != NULL
)
2472 strlcat(buf
, p
, sizeof buf
);
2476 strlcpy(buf
, "notty", sizeof buf
);
2481 session_proctitle(Session
*s
)
2484 error("no user for session %d", s
->self
);
2486 setproctitle("%s@%s", s
->pw
->pw_name
, session_tty_list());
2490 session_setup_x11fwd(Session
*s
)
2493 char display
[512], auth_display
[512];
2494 char hostname
[MAXHOSTNAMELEN
];
2497 if (no_x11_forwarding_flag
) {
2498 packet_send_debug("X11 forwarding disabled in user configuration file.");
2501 if (!options
.x11_forwarding
) {
2502 debug("X11 forwarding disabled in server configuration file.");
2505 if (!options
.xauth_location
||
2506 (stat(options
.xauth_location
, &st
) == -1)) {
2507 packet_send_debug("No xauth program; cannot forward with spoofing.");
2510 if (options
.use_login
) {
2511 packet_send_debug("X11 forwarding disabled; "
2512 "not compatible with UseLogin=yes.");
2515 if (s
->display
!= NULL
) {
2516 debug("X11 display already set.");
2519 if (x11_create_display_inet(options
.x11_display_offset
,
2520 options
.x11_use_localhost
, s
->single_connection
,
2521 &s
->display_number
, &s
->x11_chanids
) == -1) {
2522 debug("x11_create_display_inet failed.");
2525 for (i
= 0; s
->x11_chanids
[i
] != -1; i
++) {
2526 channel_register_cleanup(s
->x11_chanids
[i
],
2527 session_close_single_x11
, 0);
2530 /* Set up a suitable value for the DISPLAY variable. */
2531 if (gethostname(hostname
, sizeof(hostname
)) < 0)
2532 fatal("gethostname: %.100s", strerror(errno
));
2534 * auth_display must be used as the displayname when the
2535 * authorization entry is added with xauth(1). This will be
2536 * different than the DISPLAY string for localhost displays.
2538 if (options
.x11_use_localhost
) {
2539 snprintf(display
, sizeof display
, "localhost:%u.%u",
2540 s
->display_number
, s
->screen
);
2541 snprintf(auth_display
, sizeof auth_display
, "unix:%u.%u",
2542 s
->display_number
, s
->screen
);
2543 s
->display
= xstrdup(display
);
2544 s
->auth_display
= xstrdup(auth_display
);
2546 snprintf(display
, sizeof display
, "%.400s:%u.%u", hostname
,
2547 s
->display_number
, s
->screen
);
2548 s
->display
= xstrdup(display
);
2549 s
->auth_display
= xstrdup(display
);
2556 do_authenticated2(Authctxt
*authctxt
)
2558 server_loop2(authctxt
);
2562 do_cleanup(Authctxt
*authctxt
)
2564 static int called
= 0;
2566 debug("do_cleanup");
2568 /* no cleanup if we're in the child for login shell */
2572 /* avoid double cleanup */
2577 if (authctxt
== NULL
|| !authctxt
->authenticated
)
2580 if (options
.kerberos_ticket_cleanup
)
2581 krb4_cleanup_proc(authctxt
);
2584 if (options
.kerberos_ticket_cleanup
&&
2586 krb5_cleanup_proc(authctxt
);
2590 if (compat20
&& options
.gss_cleanup_creds
)
2591 ssh_gssapi_cleanup_creds();
2595 if (options
.use_pam
) {
2597 sshpam_thread_cleanup();
2601 /* remove agent socket */
2602 auth_sock_cleanup_proc(authctxt
->pw
);
2605 * Cleanup ptys/utmp only if privsep is disabled,
2606 * or if running in monitor.
2608 if (!use_privsep
|| mm_is_monitor())
2609 session_destroy_all(session_pty_cleanup2
);