1 /* $NetBSD: session.c,v 1.48 2008/06/22 15:42:50 christos Exp $ */
2 /* $OpenBSD: session.c,v 1.241 2008/06/16 13:22:53 dtucker 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.48 2008/06/22 15:42:50 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"
95 Session
*session_new(void);
96 void session_set_fds(Session
*, int, int, int, int);
97 void session_pty_cleanup(Session
*);
98 void session_proctitle(Session
*);
99 int session_setup_x11fwd(Session
*);
100 int do_exec_pty(Session
*, const char *);
101 int do_exec_no_pty(Session
*, const char *);
102 int do_exec(Session
*, const char *);
103 void do_login(Session
*, const char *);
104 void do_child(Session
*, const char *);
106 int check_quietlogin(Session
*, const char *);
108 static void do_authenticated1(Authctxt
*);
109 static void do_authenticated2(Authctxt
*);
111 static int session_pty_req(Session
*);
114 extern ServerOptions options
;
115 extern char *__progname
;
116 extern int log_stderr
;
117 extern int debug_flag
;
118 extern u_int utmp_len
;
119 extern int startup_pipe
;
120 extern void destroy_sensitive_data(void);
121 extern Buffer loginmsg
;
123 /* original command from peer. */
124 const char *original_command
= NULL
;
127 static int sessions_first_unused
= -1;
128 static int sessions_nalloc
= 0;
129 static Session
*sessions
= NULL
;
131 #define SUBSYSTEM_NONE 0
132 #define SUBSYSTEM_EXT 1
133 #define SUBSYSTEM_INT_SFTP 2
135 #ifdef HAVE_LOGIN_CAP
139 static int is_child
= 0;
141 /* Name and directory of socket for authentication agent forwarding. */
142 static char *auth_sock_name
= NULL
;
143 static char *auth_sock_dir
= NULL
;
145 /* removes the agent forwarding socket */
148 auth_sock_cleanup_proc(struct passwd
*pw
)
150 if (auth_sock_name
!= NULL
) {
151 temporarily_use_uid(pw
);
152 unlink(auth_sock_name
);
153 rmdir(auth_sock_dir
);
154 auth_sock_name
= NULL
;
160 auth_input_request_forwarding(struct passwd
* pw
)
164 struct sockaddr_un sunaddr
;
166 if (auth_sock_name
!= NULL
) {
167 error("authentication forwarding requested twice.");
171 /* Temporarily drop privileged uid for mkdir/bind. */
172 temporarily_use_uid(pw
);
174 /* Allocate a buffer for the socket name, and format the name. */
175 auth_sock_dir
= xstrdup("/tmp/ssh-XXXXXXXXXX");
177 /* Create private directory for socket */
178 if (mkdtemp(auth_sock_dir
) == NULL
) {
179 packet_send_debug("Agent forwarding disabled: "
180 "mkdtemp() failed: %.100s", strerror(errno
));
182 xfree(auth_sock_dir
);
183 auth_sock_dir
= NULL
;
187 xasprintf(&auth_sock_name
, "%s/agent.%ld",
188 auth_sock_dir
, (long) getpid());
190 /* Create the socket. */
191 sock
= socket(AF_UNIX
, SOCK_STREAM
, 0);
193 error("socket: %.100s", strerror(errno
));
198 /* Bind it to the name. */
199 memset(&sunaddr
, 0, sizeof(sunaddr
));
200 sunaddr
.sun_family
= AF_UNIX
;
201 strlcpy(sunaddr
.sun_path
, auth_sock_name
, sizeof(sunaddr
.sun_path
));
203 if (bind(sock
, (struct sockaddr
*)&sunaddr
, sizeof(sunaddr
)) < 0) {
204 error("bind: %.100s", strerror(errno
));
209 /* Restore the privileged uid. */
212 /* Start listening on the socket. */
213 if (listen(sock
, SSH_LISTEN_BACKLOG
) < 0) {
214 error("listen: %.100s", strerror(errno
));
218 /* Allocate a channel for the authentication agent socket. */
219 /* this shouldn't matter if its hpn or not - cjr */
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
));
228 if (auth_sock_name
!= NULL
)
229 xfree(auth_sock_name
);
230 if (auth_sock_dir
!= NULL
) {
231 rmdir(auth_sock_dir
);
232 xfree(auth_sock_dir
);
236 auth_sock_name
= NULL
;
237 auth_sock_dir
= NULL
;
242 display_loginmsg(void)
244 if (buffer_len(&loginmsg
) > 0) {
245 buffer_append(&loginmsg
, "\0", 1);
246 printf("%s", (char *)buffer_ptr(&loginmsg
));
247 buffer_clear(&loginmsg
);
252 do_authenticated(Authctxt
*authctxt
)
254 setproctitle("%s", authctxt
->pw
->pw_name
);
256 /* setup the channel layer */
257 if (!no_port_forwarding_flag
&& options
.allow_tcp_forwarding
)
258 channel_permit_all_opens();
261 do_authenticated2(authctxt
);
263 do_authenticated1(authctxt
);
265 do_cleanup(authctxt
);
269 * Prepares for an interactive session. This is called after the user has
270 * been successfully authenticated. During this message exchange, pseudo
271 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
272 * are requested, etc.
275 do_authenticated1(Authctxt
*authctxt
)
279 int success
, type
, screen_flag
;
280 int enable_compression_after_reply
= 0;
281 u_int proto_len
, data_len
, dlen
, compression_level
= 0;
285 error("no more sessions");
288 s
->authctxt
= authctxt
;
289 s
->pw
= authctxt
->pw
;
292 * We stay in this loop until the client requests to execute a shell
298 /* Get a packet from the client. */
299 type
= packet_read();
301 /* Process the packet. */
303 case SSH_CMSG_REQUEST_COMPRESSION
:
304 compression_level
= packet_get_int();
306 if (compression_level
< 1 || compression_level
> 9) {
307 packet_send_debug("Received invalid compression level %d.",
311 if (options
.compression
== COMP_NONE
) {
312 debug2("compression disabled");
315 /* Enable compression after we have responded with SUCCESS. */
316 enable_compression_after_reply
= 1;
320 case SSH_CMSG_REQUEST_PTY
:
321 success
= session_pty_req(s
);
324 case SSH_CMSG_X11_REQUEST_FORWARDING
:
325 s
->auth_proto
= packet_get_string(&proto_len
);
326 s
->auth_data
= packet_get_string(&data_len
);
328 screen_flag
= packet_get_protocol_flags() &
329 SSH_PROTOFLAG_SCREEN_NUMBER
;
330 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag
);
332 if (packet_remaining() == 4) {
334 debug2("Buggy client: "
335 "X11 screen flag missing");
336 s
->screen
= packet_get_int();
341 success
= session_setup_x11fwd(s
);
343 xfree(s
->auth_proto
);
345 s
->auth_proto
= NULL
;
350 case SSH_CMSG_AGENT_REQUEST_FORWARDING
:
351 if (!options
.allow_agent_forwarding
||
352 no_agent_forwarding_flag
|| compat13
) {
353 debug("Authentication agent forwarding not permitted for this authentication.");
356 debug("Received authentication agent forwarding request.");
357 success
= auth_input_request_forwarding(s
->pw
);
360 case SSH_CMSG_PORT_FORWARD_REQUEST
:
361 if (no_port_forwarding_flag
) {
362 debug("Port forwarding not permitted for this authentication.");
365 if (!options
.allow_tcp_forwarding
) {
366 debug("Port forwarding not permitted.");
369 debug("Received TCP/IP port forwarding request.");
370 if (channel_input_port_forward_request(s
->pw
->pw_uid
== 0,
371 options
.gateway_ports
) < 0) {
372 debug("Port forwarding failed.");
378 case SSH_CMSG_MAX_PACKET_SIZE
:
379 if (packet_set_maxsize(packet_get_int()) > 0)
383 #if defined(AFS) || defined(KRB5)
384 case SSH_CMSG_HAVE_KERBEROS_TGT
:
385 if (!options
.kerberos_tgt_passing
) {
386 verbose("Kerberos TGT passing disabled.");
388 char *kdata
= packet_get_string(&dlen
);
391 /* XXX - 0x41, see creds_to_radix version */
392 if (kdata
[0] != 0x41) {
398 if (auth_krb5_tgt(s
->authctxt
, &tgt
))
401 verbose("Kerberos v5 TGT refused for %.100s", s
->authctxt
->user
);
405 if (auth_krb4_tgt(s
->authctxt
, kdata
))
408 verbose("Kerberos v4 TGT refused for %.100s", s
->authctxt
->user
);
414 #endif /* AFS || KRB5 */
417 case SSH_CMSG_HAVE_AFS_TOKEN
:
418 if (!options
.afs_token_passing
|| !k_hasafs()) {
419 verbose("AFS token passing disabled.");
421 /* Accept AFS token. */
422 char *token
= packet_get_string(&dlen
);
425 if (auth_afs_token(s
->authctxt
, token
))
428 verbose("AFS token refused for %.100s",
435 case SSH_CMSG_EXEC_SHELL
:
436 case SSH_CMSG_EXEC_CMD
:
437 if (type
== SSH_CMSG_EXEC_CMD
) {
438 command
= packet_get_string(&dlen
);
439 debug("Exec command '%.500s'", command
);
440 if (do_exec(s
, command
) != 0)
442 "command execution failed");
445 if (do_exec(s
, NULL
) != 0)
447 "shell execution failed");
455 * Any unknown messages in this phase are ignored,
456 * and a failure message is returned.
458 logit("Unknown packet type received after authentication: %d", type
);
460 packet_start(success
? SSH_SMSG_SUCCESS
: SSH_SMSG_FAILURE
);
464 /* Enable compression now that we have replied if appropriate. */
465 if (enable_compression_after_reply
) {
466 enable_compression_after_reply
= 0;
467 packet_start_compression(compression_level
);
474 * This is called to fork and execute a command when we have no tty. This
475 * will call do_child from the child, and server_loop from the parent after
476 * setting up file descriptors and such.
479 do_exec_no_pty(Session
*s
, const char *command
)
483 int pin
[2], pout
[2], perr
[2];
485 /* Allocate pipes for communicating with the program. */
487 error("%s: pipe in: %.100s", __func__
, strerror(errno
));
490 if (pipe(pout
) < 0) {
491 error("%s: pipe out: %.100s", __func__
, strerror(errno
));
496 if (pipe(perr
) < 0) {
497 error("%s: pipe err: %.100s", __func__
, strerror(errno
));
505 int inout
[2], err
[2];
507 /* Uses socket pairs to communicate with the program. */
508 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, inout
) < 0) {
509 error("%s: socketpair #1: %.100s", __func__
, strerror(errno
));
512 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, err
) < 0) {
513 error("%s: socketpair #2: %.100s", __func__
, strerror(errno
));
521 fatal("do_exec_no_pty: no session");
523 session_proctitle(s
);
527 if (options
.use_pam
&& !use_privsep
)
532 /* Fork the child. */
533 switch ((pid
= fork())) {
535 error("%s: fork: %.100s", __func__
, strerror(errno
));
553 /* Child. Reinitialize the log since the pid has changed. */
554 log_init(__progname
, options
.log_level
,
555 options
.log_facility
, log_stderr
);
558 * Create a new session and process group since the 4.4BSD
559 * setlogin() affects the entire process group.
562 error("setsid failed: %.100s", strerror(errno
));
566 * Redirect stdin. We close the parent side of the socket
567 * pair, and make the child side the standard input.
570 if (dup2(pin
[0], 0) < 0)
571 perror("dup2 stdin");
574 /* Redirect stdout. */
576 if (dup2(pout
[1], 1) < 0)
577 perror("dup2 stdout");
580 /* Redirect stderr. */
582 if (dup2(perr
[1], 2) < 0)
583 perror("dup2 stderr");
587 * Redirect stdin, stdout, and stderr. Stdin and stdout will
588 * use the same socket, as some programs (particularly rdist)
589 * seem to depend on it.
593 if (dup2(inout
[0], 0) < 0) /* stdin */
594 perror("dup2 stdin");
595 if (dup2(inout
[0], 1) < 0) /* stdout (same as stdin) */
596 perror("dup2 stdout");
598 if (dup2(err
[0], 2) < 0) /* stderr */
599 perror("dup2 stderr");
603 /* Do processing for the child (exec command etc). */
604 do_child(s
, command
);
611 /* Set interactive/non-interactive mode. */
612 packet_set_interactive(s
->display
!= NULL
);
615 /* We are the parent. Close the child sides of the pipes. */
621 if (s
->is_subsystem
) {
625 session_set_fds(s
, pin
[1], pout
[0], perr
[0], 0);
627 /* Enter the interactive session. */
628 server_loop(pid
, pin
[1], pout
[0], perr
[0]);
629 /* server_loop has closed pin[1], pout[0], and perr[0]. */
632 /* We are the parent. Close the child sides of the socket pairs. */
637 * Enter the interactive session. Note: server_loop must be able to
638 * handle the case that fdin and fdout are the same.
641 session_set_fds(s
, inout
[1], inout
[1],
642 s
->is_subsystem
? -1 : err
[1], 0);
646 server_loop(pid
, inout
[1], inout
[1], err
[1]);
647 /* server_loop has closed inout[1] and err[1]. */
654 * This is called to fork and execute a command when we have a tty. This
655 * will call do_child from the child, and server_loop from the parent after
656 * setting up file descriptors, controlling tty, updating wtmp, utmp,
657 * lastlog, and other such operations.
660 do_exec_pty(Session
*s
, const char *command
)
662 int fdout
, ptyfd
, ttyfd
, ptymaster
;
666 fatal("do_exec_pty: no session");
671 if (options
.use_pam
) {
672 do_pam_set_tty(s
->tty
);
679 * Create another descriptor of the pty master side for use as the
680 * standard input. We could use the original descriptor, but this
681 * simplifies code in server_loop. The descriptor is bidirectional.
682 * Do this before forking (and cleanup in the child) so as to
683 * detect and gracefully fail out-of-fd conditions.
685 if ((fdout
= dup(ptyfd
)) < 0) {
686 error("%s: dup #1: %s", __func__
, strerror(errno
));
691 /* we keep a reference to the pty master */
692 if ((ptymaster
= dup(ptyfd
)) < 0) {
693 error("%s: dup #2: %s", __func__
, strerror(errno
));
700 /* Fork the child. */
701 switch ((pid
= fork())) {
703 error("%s: fork: %.100s", __func__
, strerror(errno
));
715 /* Child. Reinitialize the log because the pid has changed. */
716 log_init(__progname
, options
.log_level
,
717 options
.log_facility
, log_stderr
);
718 /* Close the master side of the pseudo tty. */
721 /* Make the pseudo tty our controlling tty. */
722 pty_make_controlling_tty(&ttyfd
, s
->tty
);
724 /* Redirect stdin/stdout/stderr from the pseudo tty. */
725 if (dup2(ttyfd
, 0) < 0)
726 error("dup2 stdin: %s", strerror(errno
));
727 if (dup2(ttyfd
, 1) < 0)
728 error("dup2 stdout: %s", strerror(errno
));
729 if (dup2(ttyfd
, 2) < 0)
730 error("dup2 stderr: %s", strerror(errno
));
732 /* Close the extra descriptor for the pseudo tty. */
735 /* record login, etc. similar to login(1) */
736 if (!(options
.use_login
&& command
== NULL
))
737 do_login(s
, command
);
740 * Do common processing for the child, such as execing
743 do_child(s
, command
);
750 /* Parent. Close the slave side of the pseudo tty. */
753 /* Enter interactive session. */
754 s
->ptymaster
= ptymaster
;
755 packet_set_interactive(1);
757 session_set_fds(s
, ptyfd
, fdout
, -1, 1);
759 server_loop(pid
, ptyfd
, fdout
, -1);
760 /* server_loop _has_ closed ptyfd and fdout. */
766 * This is called to fork and execute a command. If another command is
767 * to be forced, execute that instead.
770 do_exec(Session
*s
, const char *command
)
774 if (options
.adm_forced_command
) {
775 original_command
= command
;
776 command
= options
.adm_forced_command
;
777 if (strcmp(INTERNAL_SFTP_NAME
, command
) == 0)
778 s
->is_subsystem
= SUBSYSTEM_INT_SFTP
;
779 else if (s
->is_subsystem
)
780 s
->is_subsystem
= SUBSYSTEM_EXT
;
781 debug("Forced command (config) '%.900s'", command
);
782 } else if (forced_command
) {
783 original_command
= command
;
784 command
= forced_command
;
785 if (strcmp(INTERNAL_SFTP_NAME
, command
) == 0)
786 s
->is_subsystem
= SUBSYSTEM_INT_SFTP
;
787 else if (s
->is_subsystem
)
788 s
->is_subsystem
= SUBSYSTEM_EXT
;
789 debug("Forced command (key option) '%.900s'", command
);
793 if (options
.gss_authentication
) {
794 temporarily_use_uid(s
->pw
);
795 ssh_gssapi_storecreds();
800 ret
= do_exec_pty(s
, command
);
802 ret
= do_exec_no_pty(s
, command
);
804 original_command
= NULL
;
807 * Clear loginmsg: it's the child's responsibility to display
808 * it to the user, otherwise multiple sessions may accumulate
809 * multiple copies of the login messages.
811 buffer_clear(&loginmsg
);
817 /* administrative, login(1)-like work */
819 do_login(Session
*s
, const char *command
)
822 struct sockaddr_storage from
;
823 struct passwd
* pw
= s
->pw
;
824 pid_t pid
= getpid();
827 * Get IP address of client. If the connection is not a socket, let
828 * the address be 0.0.0.0.
830 memset(&from
, 0, sizeof(from
));
831 fromlen
= sizeof(from
);
832 if (packet_connection_is_on_socket()) {
833 if (getpeername(packet_get_connection_in(),
834 (struct sockaddr
*)&from
, &fromlen
) < 0) {
835 debug("getpeername: %.100s", strerror(errno
));
840 /* Record that there was a login on that tty from the remote host. */
842 record_login(pid
, s
->tty
, pw
->pw_name
, pw
->pw_uid
,
843 get_remote_name_or_ip(utmp_len
,
845 (struct sockaddr
*)&from
, fromlen
);
849 * If password change is needed, do it now.
850 * This needs to occur before the ~/.hushlogin check.
852 if (options
.use_pam
&& !use_privsep
&& s
->authctxt
->force_pwchange
) {
855 s
->authctxt
->force_pwchange
= 0;
856 /* XXX - signal [net] parent to enable forwardings */
860 if (check_quietlogin(s
, command
))
869 * Display the message of the day.
877 if (options
.print_motd
) {
878 #ifdef HAVE_LOGIN_CAP
879 f
= fopen(login_getcapstr(lc
, "welcome", "/etc/motd",
882 f
= fopen("/etc/motd", "r");
885 while (fgets(buf
, sizeof(buf
), f
))
894 * Check for quiet login, either .hushlogin or command given.
897 check_quietlogin(Session
*s
, const char *command
)
900 struct passwd
*pw
= s
->pw
;
903 /* Return 1 if .hushlogin exists or a command given. */
906 snprintf(buf
, sizeof(buf
), "%.200s/.hushlogin", pw
->pw_dir
);
907 #ifdef HAVE_LOGIN_CAP
908 if (login_getcapbool(lc
, "hushlogin", 0) || stat(buf
, &st
) >= 0)
911 if (stat(buf
, &st
) >= 0)
918 * Sets the value of the given variable in the environment. If the variable
919 * already exists, its value is overriden.
922 child_set_env(char ***envp
, u_int
*envsizep
, const char *name
,
930 * Find the slot where the value should be stored. If the variable
931 * already exists, we reuse the slot; otherwise we append a new slot
932 * at the end of the array, expanding if necessary.
935 namelen
= strlen(name
);
936 for (i
= 0; env
[i
]; i
++)
937 if (strncmp(env
[i
], name
, namelen
) == 0 && env
[i
][namelen
] == '=')
940 /* Reuse the slot. */
943 /* New variable. Expand if necessary. */
945 if (i
>= envsize
- 1) {
947 fatal("child_set_env: too many env vars");
949 env
= (*envp
) = xrealloc(env
, envsize
, sizeof(char *));
952 /* Need to set the NULL pointer at end of array beyond the new slot. */
956 /* Allocate space and format the variable in the appropriate slot. */
957 env
[i
] = xmalloc(strlen(name
) + 1 + strlen(value
) + 1);
958 snprintf(env
[i
], strlen(name
) + 1 + strlen(value
) + 1, "%s=%s", name
, value
);
961 #ifdef HAVE_LOGIN_CAP
963 * Sets any environment variables specified in login.conf.
965 * NetBSD: login_cap.c,v 1.11 2001/07/22 13:34:01 wiz Exp
966 * Modified to use child_set_env instead of setenv.
969 lc_setuserenv(char ***env
, u_int
*envsize
, login_cap_t
*lc
)
971 const char *stop
= ", \t";
975 char *str
= login_getcapstr(lc
, "setenv", NULL
, NULL
);
977 if (str
== NULL
|| *str
== '\0')
980 /* count the sub-strings */
981 for (i
= 1, ptr
= str
; *ptr
; i
++) {
982 ptr
+= strcspn(ptr
, stop
);
987 /* allocate ptr array and string */
989 res
= malloc(count
* sizeof(char *) + strlen(str
) + 1);
994 ptr
= (char *)res
+ count
* sizeof(char *);
998 for (i
= 0; *ptr
&& i
< count
; i
++) {
1000 ptr
+= strcspn(ptr
, stop
);
1007 for (i
= 0; i
< count
&& res
[i
]; i
++) {
1008 if (*res
[i
] != '\0') {
1009 if ((ptr
= strchr(res
[i
], '=')) != NULL
)
1013 child_set_env(env
, envsize
, res
[i
], ptr
);
1023 * Reads environment variables from the given file and adds/overrides them
1024 * into the environment. If the file does not exist, this does nothing.
1025 * Otherwise, it must consist of empty lines, comments (line starts with '#')
1026 * and assignments of the form name=value. No other forms are allowed.
1029 read_environment_file(char ***env
, u_int
*envsize
,
1030 const char *filename
)
1037 f
= fopen(filename
, "r");
1041 while (fgets(buf
, sizeof(buf
), f
)) {
1042 if (++lineno
> 1000)
1043 fatal("Too many lines in environment file %s", filename
);
1044 for (cp
= buf
; *cp
== ' ' || *cp
== '\t'; cp
++)
1046 if (!*cp
|| *cp
== '#' || *cp
== '\n')
1049 cp
[strcspn(cp
, "\n")] = '\0';
1051 value
= strchr(cp
, '=');
1052 if (value
== NULL
) {
1053 fprintf(stderr
, "Bad line %u in %.100s\n", lineno
,
1058 * Replace the equals sign by nul, and advance value to
1063 child_set_env(env
, envsize
, cp
, value
);
1069 void copy_environment(char **, char ***, u_int
*);
1070 void copy_environment(char **source
, char ***env
, u_int
*envsize
)
1072 char *var_name
, *var_val
;
1078 for(i
= 0; source
[i
] != NULL
; i
++) {
1079 var_name
= xstrdup(source
[i
]);
1080 if ((var_val
= strstr(var_name
, "=")) == NULL
) {
1086 debug3("Copy environment: %s=%s", var_name
, var_val
);
1087 child_set_env(env
, envsize
, var_name
, var_val
);
1095 do_setup_env(Session
*s
, const char *shell
)
1100 struct passwd
*pw
= s
->pw
;
1102 /* Initialize the environment. */
1104 env
= xcalloc(envsize
, sizeof(char *));
1108 /* Allow any GSSAPI methods that we've used to alter
1109 * the childs environment as they see fit
1111 ssh_gssapi_do_child(&env
, &envsize
);
1114 if (!options
.use_login
) {
1115 #ifdef HAVE_LOGIN_CAP
1116 lc_setuserenv(&env
, &envsize
, lc
);
1118 /* Set basic environment. */
1119 for (i
= 0; i
< s
->num_env
; i
++)
1120 child_set_env(&env
, &envsize
, s
->env
[i
].name
,
1123 child_set_env(&env
, &envsize
, "USER", pw
->pw_name
);
1124 child_set_env(&env
, &envsize
, "LOGNAME", pw
->pw_name
);
1125 child_set_env(&env
, &envsize
, "HOME", pw
->pw_dir
);
1126 #ifdef HAVE_LOGIN_CAP
1127 if (setusercontext(lc
, pw
, pw
->pw_uid
, LOGIN_SETPATH
) < 0)
1128 child_set_env(&env
, &envsize
, "PATH", _PATH_STDPATH
);
1130 child_set_env(&env
, &envsize
, "PATH", getenv("PATH"));
1132 child_set_env(&env
, &envsize
, "PATH", _PATH_STDPATH
);
1135 snprintf(buf
, sizeof buf
, "%.200s/%.50s",
1136 _PATH_MAILDIR
, pw
->pw_name
);
1137 child_set_env(&env
, &envsize
, "MAIL", buf
);
1139 /* Normal systems set SHELL by default. */
1140 child_set_env(&env
, &envsize
, "SHELL", shell
);
1143 child_set_env(&env
, &envsize
, "TZ", getenv("TZ"));
1145 /* Set custom environment options from RSA authentication. */
1146 if (!options
.use_login
) {
1147 while (custom_environment
) {
1148 struct envstring
*ce
= custom_environment
;
1151 for (i
= 0; str
[i
] != '=' && str
[i
]; i
++)
1153 if (str
[i
] == '=') {
1155 child_set_env(&env
, &envsize
, str
, str
+ i
+ 1);
1157 custom_environment
= ce
->next
;
1163 /* SSH_CLIENT deprecated */
1164 snprintf(buf
, sizeof buf
, "%.50s %d %d",
1165 get_remote_ipaddr(), get_remote_port(), get_local_port());
1166 child_set_env(&env
, &envsize
, "SSH_CLIENT", buf
);
1168 laddr
= get_local_ipaddr(packet_get_connection_in());
1169 snprintf(buf
, sizeof buf
, "%.50s %d %.50s %d",
1170 get_remote_ipaddr(), get_remote_port(), laddr
, get_local_port());
1172 child_set_env(&env
, &envsize
, "SSH_CONNECTION", buf
);
1175 child_set_env(&env
, &envsize
, "SSH_TTY", s
->tty
);
1177 child_set_env(&env
, &envsize
, "TERM", s
->term
);
1179 child_set_env(&env
, &envsize
, "DISPLAY", s
->display
);
1180 if (original_command
)
1181 child_set_env(&env
, &envsize
, "SSH_ORIGINAL_COMMAND",
1184 if (s
->authctxt
->krb4_ticket_file
)
1185 child_set_env(&env
, &envsize
, "KRBTKFILE",
1186 s
->authctxt
->krb4_ticket_file
);
1189 if (s
->authctxt
->krb5_ticket_file
)
1190 child_set_env(&env
, &envsize
, "KRB5CCNAME",
1191 s
->authctxt
->krb5_ticket_file
);
1195 * Pull in any environment variables that may have
1198 if (options
.use_pam
) {
1201 p
= fetch_pam_child_environment();
1202 copy_environment(p
, &env
, &envsize
);
1203 free_pam_environment(p
);
1205 p
= fetch_pam_environment();
1206 copy_environment(p
, &env
, &envsize
);
1207 free_pam_environment(p
);
1209 #endif /* USE_PAM */
1211 if (auth_sock_name
!= NULL
)
1212 child_set_env(&env
, &envsize
, SSH_AUTHSOCKET_ENV_NAME
,
1215 /* read $HOME/.ssh/environment. */
1216 if (options
.permit_user_env
&& !options
.use_login
) {
1217 snprintf(buf
, sizeof buf
, "%.200s/.ssh/environment",
1219 read_environment_file(&env
, &envsize
, buf
);
1222 /* dump the environment */
1223 fprintf(stderr
, "Environment:\n");
1224 for (i
= 0; env
[i
]; i
++)
1225 fprintf(stderr
, " %.200s\n", env
[i
]);
1231 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1232 * first in this order).
1235 do_rc_files(Session
*s
, const char *shell
)
1243 s
->display
!= NULL
&& s
->auth_proto
!= NULL
&& s
->auth_data
!= NULL
;
1245 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1246 if (!s
->is_subsystem
&& options
.adm_forced_command
== NULL
&&
1247 !no_user_rc
&& stat(_PATH_SSH_USER_RC
, &st
) >= 0) {
1248 snprintf(cmd
, sizeof cmd
, "%s -c '%s %s'",
1249 shell
, _PATH_BSHELL
, _PATH_SSH_USER_RC
);
1251 fprintf(stderr
, "Running %s\n", cmd
);
1252 f
= popen(cmd
, "w");
1255 fprintf(f
, "%s %s\n", s
->auth_proto
,
1259 fprintf(stderr
, "Could not run %s\n",
1261 } else if (stat(_PATH_SSH_SYSTEM_RC
, &st
) >= 0) {
1263 fprintf(stderr
, "Running %s %s\n", _PATH_BSHELL
,
1264 _PATH_SSH_SYSTEM_RC
);
1265 f
= popen(_PATH_BSHELL
" " _PATH_SSH_SYSTEM_RC
, "w");
1268 fprintf(f
, "%s %s\n", s
->auth_proto
,
1272 fprintf(stderr
, "Could not run %s\n",
1273 _PATH_SSH_SYSTEM_RC
);
1274 } else if (do_xauth
&& options
.xauth_location
!= NULL
) {
1275 /* Add authority data to .Xauthority if appropriate. */
1278 "Running %.500s remove %.100s\n",
1279 options
.xauth_location
, s
->auth_display
);
1281 "%.500s add %.100s %.100s %.100s\n",
1282 options
.xauth_location
, s
->auth_display
,
1283 s
->auth_proto
, s
->auth_data
);
1285 snprintf(cmd
, sizeof cmd
, "%s -q -",
1286 options
.xauth_location
);
1287 f
= popen(cmd
, "w");
1289 fprintf(f
, "remove %s\n",
1291 fprintf(f
, "add %s %s %s\n",
1292 s
->auth_display
, s
->auth_proto
,
1296 fprintf(stderr
, "Could not run %s\n",
1303 do_nologin(struct passwd
*pw
)
1308 #ifdef HAVE_LOGIN_CAP
1309 if (!login_getcapbool(lc
, "ignorenologin", 0) && pw
->pw_uid
)
1310 f
= fopen(login_getcapstr(lc
, "nologin", _PATH_NOLOGIN
,
1311 _PATH_NOLOGIN
), "r");
1314 f
= fopen(_PATH_NOLOGIN
, "r");
1317 /* /etc/nologin exists. Print its contents and exit. */
1318 logit("User %.100s not allowed because %s exists",
1319 pw
->pw_name
, _PATH_NOLOGIN
);
1320 while (fgets(buf
, sizeof(buf
), f
))
1328 * Chroot into a directory after checking it for safety: all path components
1329 * must be root-owned directories with strict permissions.
1332 safely_chroot(const char *path
, uid_t uid
)
1335 char component
[MAXPATHLEN
];
1339 fatal("chroot path does not begin at root");
1340 if (strlen(path
) >= sizeof(component
))
1341 fatal("chroot path too long");
1344 * Descend the path, checking that each component is a
1345 * root-owned directory with strict permissions.
1347 for (cp
= path
; cp
!= NULL
;) {
1348 if ((cp
= strchr(cp
, '/')) == NULL
)
1349 strlcpy(component
, path
, sizeof(component
));
1352 memcpy(component
, path
, cp
- path
);
1353 component
[cp
- path
] = '\0';
1356 debug3("%s: checking '%s'", __func__
, component
);
1358 if (stat(component
, &st
) != 0)
1359 fatal("%s: stat(\"%s\"): %s", __func__
,
1360 component
, strerror(errno
));
1361 if (st
.st_uid
!= 0 || (st
.st_mode
& 022) != 0)
1362 fatal("bad ownership or modes for chroot "
1363 "directory %s\"%s\"",
1364 cp
== NULL
? "" : "component ", component
);
1365 if (!S_ISDIR(st
.st_mode
))
1366 fatal("chroot path %s\"%s\" is not a directory",
1367 cp
== NULL
? "" : "component ", component
);
1371 if (chdir(path
) == -1)
1372 fatal("Unable to chdir to chroot path \"%s\": "
1373 "%s", path
, strerror(errno
));
1374 if (chroot(path
) == -1)
1375 fatal("chroot(\"%s\"): %s", path
, strerror(errno
));
1376 if (chdir("/") == -1)
1377 fatal("%s: chdir(/) after chroot: %s",
1378 __func__
, strerror(errno
));
1379 verbose("Changed root directory to \"%s\"", path
);
1382 /* Set login name, uid, gid, and groups. */
1384 do_setusercontext(struct passwd
*pw
)
1386 char *chroot_path
, *tmp
;
1388 if (getuid() == 0 || geteuid() == 0) {
1389 #ifdef HAVE_LOGIN_CAP
1391 if (options
.use_pam
) {
1392 do_pam_setcred(use_privsep
);
1394 # endif /* USE_PAM */
1395 /* Prepare groups */
1396 if (setusercontext(lc
, pw
, pw
->pw_uid
,
1397 (LOGIN_SETALL
& ~(LOGIN_SETPATH
|LOGIN_SETUSER
))) < 0) {
1398 perror("unable to set user context");
1403 if (setlogin(pw
->pw_name
) < 0)
1404 error("setlogin failed: %s", strerror(errno
));
1405 if (setgid(pw
->pw_gid
) < 0) {
1409 /* Initialize the group list. */
1410 if (initgroups(pw
->pw_name
, pw
->pw_gid
) < 0) {
1411 perror("initgroups");
1417 * PAM credentials may take the form of supplementary groups.
1418 * These will have been wiped by the above initgroups() call.
1419 * Reestablish them here.
1421 if (options
.use_pam
) {
1422 do_pam_setcred(use_privsep
);
1424 # endif /* USE_PAM */
1426 if (options
.chroot_directory
!= NULL
&&
1427 strcasecmp(options
.chroot_directory
, "none") != 0) {
1428 tmp
= tilde_expand_filename(options
.chroot_directory
,
1430 chroot_path
= percent_expand(tmp
, "h", pw
->pw_dir
,
1431 "u", pw
->pw_name
, (char *)NULL
);
1432 safely_chroot(chroot_path
, pw
->pw_uid
);
1437 #ifdef HAVE_LOGIN_CAP
1439 if (setusercontext(lc
, pw
, pw
->pw_uid
, LOGIN_SETUSER
) < 0) {
1440 perror("unable to set user context (setuser)");
1444 /* Permanently switch to the desired uid. */
1445 permanently_set_uid(pw
);
1448 if (getuid() != pw
->pw_uid
|| geteuid() != pw
->pw_uid
)
1449 fatal("Failed to set uids to %u.", (u_int
) pw
->pw_uid
);
1453 do_pwchange(Session
*s
)
1456 fprintf(stderr
, "WARNING: Your password has expired.\n");
1457 if (s
->ttyfd
!= -1) {
1459 "You must change your password now and login again!\n");
1460 execl(_PATH_PASSWD_PROG
, "passwd", (char *)NULL
);
1464 "Password change required but no TTY available.\n");
1470 launch_login(struct passwd
*pw
, const char *hostname
)
1472 /* Launch login(1). */
1474 execl("/usr/bin/login", "login", "-h", hostname
,
1475 "-p", "-f", "--", pw
->pw_name
, (char *)NULL
);
1477 /* Login couldn't be executed, die. */
1484 child_close_fds(void)
1488 if (packet_get_connection_in() == packet_get_connection_out())
1489 close(packet_get_connection_in());
1491 close(packet_get_connection_in());
1492 close(packet_get_connection_out());
1495 * Close all descriptors related to channels. They will still remain
1496 * open in the parent.
1498 /* XXX better use close-on-exec? -markus */
1499 channel_close_all();
1502 * Close any extra file descriptors. Note that there may still be
1503 * descriptors left by system functions. They will be closed later.
1508 * Close any extra open file descriptors so that we don't have them
1509 * hanging around in clients. Note that we want to do this after
1510 * initgroups, because at least on Solaris 2.3 it leaves file
1513 for (i
= 3; i
< 64; i
++)
1518 * Performs common processing for the child, such as setting up the
1519 * environment, closing extra file descriptors, setting the user and group
1520 * ids, and executing the command or shell.
1524 do_child(Session
*s
, const char *command
)
1526 extern char **environ
;
1528 char *argv
[ARGV_MAX
];
1529 const char *shell
, *shell0
, *hostname
= NULL
;
1530 struct passwd
*pw
= s
->pw
;
1533 /* remove hostkey from the child's memory */
1534 destroy_sensitive_data();
1536 /* Force a password change */
1537 if (s
->authctxt
->force_pwchange
) {
1538 do_setusercontext(pw
);
1544 /* login(1) is only called if we execute the login shell */
1545 if (options
.use_login
&& command
!= NULL
)
1546 options
.use_login
= 0;
1549 * Login(1) does this as well, and it needs uid 0 for the "-h"
1550 * switch, so we let login(1) to this for us.
1552 if (!options
.use_login
) {
1554 do_setusercontext(pw
);
1556 * PAM session modules in do_setusercontext may have
1557 * generated messages, so if this in an interactive
1558 * login then display them too.
1560 if (!check_quietlogin(s
, command
))
1564 if (options
.use_pam
&& !is_pam_session_open()) {
1565 debug3("PAM session not opened, exiting");
1572 * Get the shell from the password data. An empty shell field is
1573 * legal, and means /bin/sh.
1575 shell
= (pw
->pw_shell
[0] == '\0') ? _PATH_BSHELL
: pw
->pw_shell
;
1578 * Make sure $SHELL points to the shell from the password file,
1579 * even if shell is overridden from login.conf
1581 env
= do_setup_env(s
, shell
);
1583 #ifdef HAVE_LOGIN_CAP
1584 shell
= login_getcapstr(lc
, "shell", (char *)shell
, (char *)shell
);
1587 /* we have to stash the hostname before we close our socket. */
1588 if (options
.use_login
)
1589 hostname
= get_remote_name_or_ip(utmp_len
,
1592 * Close the connection descriptors; note that this is the child, and
1593 * the server will still have the socket open, and it is important
1594 * that we do not shutdown it. Note that the descriptors cannot be
1595 * closed before building the environment, as we call
1596 * get_remote_ipaddr there.
1601 * Must take new environment into use so that .ssh/rc,
1602 * /etc/ssh/sshrc and xauth are run in the proper environment.
1608 * At this point, we check to see if AFS is active and if we have
1609 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1610 * if we can (and need to) extend the ticket into an AFS token. If
1611 * we don't do this, we run into potential problems if the user's
1612 * home directory is in AFS and it's not world-readable.
1615 if (options
.kerberos_get_afs_token
&& k_hasafs() &&
1616 (s
->authctxt
->krb5_ctx
!= NULL
)) {
1619 debug("Getting AFS token");
1623 if (k_afs_cell_of_file(pw
->pw_dir
, cell
, sizeof(cell
)) == 0)
1624 krb5_afslog(s
->authctxt
->krb5_ctx
,
1625 s
->authctxt
->krb5_fwd_ccache
, cell
, NULL
);
1627 krb5_afslog_home(s
->authctxt
->krb5_ctx
,
1628 s
->authctxt
->krb5_fwd_ccache
, NULL
, NULL
, pw
->pw_dir
);
1632 /* Change current directory to the user's home directory. */
1633 if (chdir(pw
->pw_dir
) < 0) {
1634 /* Suppress missing homedir warning for chroot case */
1635 r
= login_getcapbool(lc
, "requirehome", 0);
1636 if (r
|| options
.chroot_directory
== NULL
)
1637 fprintf(stderr
, "Could not chdir to home "
1638 "directory %s: %s\n", pw
->pw_dir
,
1644 closefrom(STDERR_FILENO
+ 1);
1646 if (!options
.use_login
)
1647 do_rc_files(s
, shell
);
1649 /* restore SIGPIPE for child */
1650 signal(SIGPIPE
, SIG_DFL
);
1652 if (s
->is_subsystem
== SUBSYSTEM_INT_SFTP
) {
1653 extern int optind
, optreset
;
1657 setproctitle("%s@internal-sftp-server", s
->pw
->pw_name
);
1658 args
= strdup(command
? command
: "sftp-server");
1659 for (i
= 0, (p
= strtok(args
, " ")); p
; (p
= strtok(NULL
, " ")))
1660 if (i
< ARGV_MAX
- 1)
1663 optind
= optreset
= 1;
1664 __progname
= argv
[0];
1665 exit(sftp_server_main(i
, argv
, s
->pw
));
1668 if (options
.use_login
) {
1669 launch_login(pw
, hostname
);
1673 /* Get the last component of the shell name. */
1674 if ((shell0
= strrchr(shell
, '/')) != NULL
)
1680 * If we have no command, execute the shell. In this case, the shell
1681 * name to be passed in argv[0] is preceded by '-' to indicate that
1682 * this is a login shell.
1687 /* Start the shell. Set initial character to '-'. */
1690 if (strlcpy(argv0
+ 1, shell0
, sizeof(argv0
) - 1)
1691 >= sizeof(argv0
) - 1) {
1697 /* Execute the shell. */
1700 execve(shell
, argv
, env
);
1702 /* Executing the shell failed. */
1707 * Execute the command using the user's shell. This uses the -c
1708 * option to execute the command.
1710 argv
[0] = (char *) shell0
;
1712 argv
[2] = (char *) command
;
1714 execve(shell
, argv
, env
);
1720 session_unused(int id
)
1722 debug3("%s: session id %d unused", __func__
, id
);
1723 if (id
>= options
.max_sessions
||
1724 id
>= sessions_nalloc
) {
1725 fatal("%s: insane session id %d (max %d nalloc %d)",
1726 __func__
, id
, options
.max_sessions
, sessions_nalloc
);
1728 bzero(&sessions
[id
], sizeof(*sessions
));
1729 sessions
[id
].self
= id
;
1730 sessions
[id
].used
= 0;
1731 sessions
[id
].chanid
= -1;
1732 sessions
[id
].ptyfd
= -1;
1733 sessions
[id
].ttyfd
= -1;
1734 sessions
[id
].ptymaster
= -1;
1735 sessions
[id
].x11_chanids
= NULL
;
1736 sessions
[id
].next_unused
= sessions_first_unused
;
1737 sessions_first_unused
= id
;
1745 if (sessions_first_unused
== -1) {
1746 if (sessions_nalloc
>= options
.max_sessions
)
1748 debug2("%s: allocate (allocated %d max %d)",
1749 __func__
, sessions_nalloc
, options
.max_sessions
);
1750 tmp
= xrealloc(sessions
, sessions_nalloc
+ 1,
1753 error("%s: cannot allocate %d sessions",
1754 __func__
, sessions_nalloc
+ 1);
1758 session_unused(sessions_nalloc
++);
1761 if (sessions_first_unused
>= sessions_nalloc
||
1762 sessions_first_unused
< 0) {
1763 fatal("%s: insane first_unused %d max %d nalloc %d",
1764 __func__
, sessions_first_unused
, options
.max_sessions
,
1768 s
= &sessions
[sessions_first_unused
];
1770 fatal("%s: session %d already used",
1771 __func__
, sessions_first_unused
);
1773 sessions_first_unused
= s
->next_unused
;
1775 s
->next_unused
= -1;
1776 debug("session_new: session %d", s
->self
);
1785 for (i
= 0; i
< sessions_nalloc
; i
++) {
1786 Session
*s
= &sessions
[i
];
1788 debug("dump: used %d next_unused %d session %d %p "
1789 "channel %d pid %ld",
1800 session_open(Authctxt
*authctxt
, int chanid
)
1802 Session
*s
= session_new();
1803 debug("session_open: channel %d", chanid
);
1805 error("no more sessions");
1808 s
->authctxt
= authctxt
;
1809 s
->pw
= authctxt
->pw
;
1810 if (s
->pw
== NULL
|| !authctxt
->valid
)
1811 fatal("no user for session %d", s
->self
);
1812 debug("session_open: session %d: link with channel %d", s
->self
, chanid
);
1818 session_by_tty(char *tty
)
1821 for (i
= 0; i
< sessions_nalloc
; i
++) {
1822 Session
*s
= &sessions
[i
];
1823 if (s
->used
&& s
->ttyfd
!= -1 && strcmp(s
->tty
, tty
) == 0) {
1824 debug("session_by_tty: session %d tty %s", i
, tty
);
1828 debug("session_by_tty: unknown tty %.100s", tty
);
1834 session_by_channel(int id
)
1837 for (i
= 0; i
< sessions_nalloc
; i
++) {
1838 Session
*s
= &sessions
[i
];
1839 if (s
->used
&& s
->chanid
== id
) {
1840 debug("session_by_channel: session %d channel %d",
1845 debug("session_by_channel: unknown channel %d", id
);
1851 session_by_x11_channel(int id
)
1855 for (i
= 0; i
< sessions_nalloc
; i
++) {
1856 Session
*s
= &sessions
[i
];
1858 if (s
->x11_chanids
== NULL
|| !s
->used
)
1860 for (j
= 0; s
->x11_chanids
[j
] != -1; j
++) {
1861 if (s
->x11_chanids
[j
] == id
) {
1862 debug("session_by_x11_channel: session %d "
1863 "channel %d", s
->self
, id
);
1868 debug("session_by_x11_channel: unknown channel %d", id
);
1874 session_by_pid(pid_t pid
)
1877 debug("session_by_pid: pid %ld", (long)pid
);
1878 for (i
= 0; i
< sessions_nalloc
; i
++) {
1879 Session
*s
= &sessions
[i
];
1880 if (s
->used
&& s
->pid
== pid
)
1883 error("session_by_pid: unknown pid %ld", (long)pid
);
1889 session_window_change_req(Session
*s
)
1891 s
->col
= packet_get_int();
1892 s
->row
= packet_get_int();
1893 s
->xpixel
= packet_get_int();
1894 s
->ypixel
= packet_get_int();
1896 pty_change_window_size(s
->ptyfd
, s
->row
, s
->col
, s
->xpixel
, s
->ypixel
);
1901 session_pty_req(Session
*s
)
1907 debug("Allocating a pty not permitted for this authentication.");
1910 if (s
->ttyfd
!= -1) {
1911 packet_disconnect("Protocol error: you already have a pty.");
1915 s
->term
= packet_get_string(&len
);
1918 s
->col
= packet_get_int();
1919 s
->row
= packet_get_int();
1921 s
->row
= packet_get_int();
1922 s
->col
= packet_get_int();
1924 s
->xpixel
= packet_get_int();
1925 s
->ypixel
= packet_get_int();
1927 if (strcmp(s
->term
, "") == 0) {
1932 /* Allocate a pty and open it. */
1933 debug("Allocating pty.");
1934 if (!PRIVSEP(pty_allocate(&s
->ptyfd
, &s
->ttyfd
, s
->tty
,
1941 error("session_pty_req: session %d alloc failed", s
->self
);
1944 debug("session_pty_req: session %d alloc %s", s
->self
, s
->tty
);
1946 /* for SSH1 the tty modes length is not given */
1948 n_bytes
= packet_remaining();
1949 tty_parse_modes(s
->ttyfd
, &n_bytes
);
1952 pty_setowner(s
->pw
, s
->tty
);
1954 /* Set window size from the packet. */
1955 pty_change_window_size(s
->ptyfd
, s
->row
, s
->col
, s
->xpixel
, s
->ypixel
);
1958 session_proctitle(s
);
1963 session_subsystem_req(Session
*s
)
1968 char *prog
, *cmd
, *subsys
= packet_get_string(&len
);
1972 logit("subsystem request for %.100s", subsys
);
1974 for (i
= 0; i
< options
.num_subsystems
; i
++) {
1975 if (strcmp(subsys
, options
.subsystem_name
[i
]) == 0) {
1976 prog
= options
.subsystem_command
[i
];
1977 cmd
= options
.subsystem_args
[i
];
1978 if (!strcmp(INTERNAL_SFTP_NAME
, prog
)) {
1979 s
->is_subsystem
= SUBSYSTEM_INT_SFTP
;
1980 } else if (stat(prog
, &st
) < 0) {
1981 error("subsystem: cannot stat %s: %s", prog
,
1985 s
->is_subsystem
= SUBSYSTEM_EXT
;
1987 debug("subsystem: exec() %s", cmd
);
1988 success
= do_exec(s
, cmd
) == 0;
1994 logit("subsystem request for %.100s failed, subsystem not found",
2002 session_x11_req(Session
*s
)
2006 if (s
->auth_proto
!= NULL
|| s
->auth_data
!= NULL
) {
2007 error("session_x11_req: session %d: "
2008 "x11 forwarding already active", s
->self
);
2011 s
->single_connection
= packet_get_char();
2012 s
->auth_proto
= packet_get_string(NULL
);
2013 s
->auth_data
= packet_get_string(NULL
);
2014 s
->screen
= packet_get_int();
2017 success
= session_setup_x11fwd(s
);
2019 xfree(s
->auth_proto
);
2020 xfree(s
->auth_data
);
2021 s
->auth_proto
= NULL
;
2022 s
->auth_data
= NULL
;
2028 session_shell_req(Session
*s
)
2031 return do_exec(s
, NULL
) == 0;
2035 session_exec_req(Session
*s
)
2039 char *command
= packet_get_string(&len
);
2041 success
= do_exec(s
, command
) == 0;
2047 session_break_req(Session
*s
)
2050 packet_get_int(); /* ignored */
2053 if (s
->ttyfd
== -1 || tcsendbreak(s
->ttyfd
, 0) < 0)
2059 session_env_req(Session
*s
)
2062 u_int name_len
, val_len
, i
;
2064 name
= packet_get_string(&name_len
);
2065 val
= packet_get_string(&val_len
);
2068 /* Don't set too many environment variables */
2069 if (s
->num_env
> 128) {
2070 debug2("Ignoring env request %s: too many env vars", name
);
2074 for (i
= 0; i
< options
.num_accept_env
; i
++) {
2075 if (match_pattern(name
, options
.accept_env
[i
])) {
2076 debug2("Setting env %d: %s=%s", s
->num_env
, name
, val
);
2077 s
->env
= xrealloc(s
->env
, s
->num_env
+ 1,
2079 s
->env
[s
->num_env
].name
= name
;
2080 s
->env
[s
->num_env
].val
= val
;
2085 debug2("Ignoring env request %s: disallowed name", name
);
2094 session_auth_agent_req(Session
*s
)
2096 static int called
= 0;
2098 if (no_agent_forwarding_flag
|| !options
.allow_agent_forwarding
) {
2099 debug("session_auth_agent_req: no_agent_forwarding_flag");
2106 return auth_input_request_forwarding(s
->pw
);
2111 session_input_channel_req(Channel
*c
, const char *rtype
)
2116 if ((s
= session_by_channel(c
->self
)) == NULL
) {
2117 logit("session_input_channel_req: no session %d req %.100s",
2121 debug("session_input_channel_req: session %d req %s", s
->self
, rtype
);
2124 * a session is in LARVAL state until a shell, a command
2125 * or a subsystem is executed
2127 if (c
->type
== SSH_CHANNEL_LARVAL
) {
2128 if (strcmp(rtype
, "shell") == 0) {
2129 success
= session_shell_req(s
);
2130 } else if (strcmp(rtype
, "exec") == 0) {
2131 success
= session_exec_req(s
);
2132 } else if (strcmp(rtype
, "pty-req") == 0) {
2133 success
= session_pty_req(s
);
2134 } else if (strcmp(rtype
, "x11-req") == 0) {
2135 success
= session_x11_req(s
);
2136 } else if (strcmp(rtype
, "auth-agent-req@openssh.com") == 0) {
2137 success
= session_auth_agent_req(s
);
2138 } else if (strcmp(rtype
, "subsystem") == 0) {
2139 success
= session_subsystem_req(s
);
2140 } else if (strcmp(rtype
, "env") == 0) {
2141 success
= session_env_req(s
);
2144 if (strcmp(rtype
, "window-change") == 0) {
2145 success
= session_window_change_req(s
);
2146 } else if (strcmp(rtype
, "break") == 0) {
2147 success
= session_break_req(s
);
2154 session_set_fds(Session
*s
, int fdin
, int fdout
, int fderr
, int is_tty
)
2157 fatal("session_set_fds: called for proto != 2.0");
2159 * now that have a child and a pipe to the child,
2160 * we can activate our channel and register the fd's
2162 if (s
->chanid
== -1)
2163 fatal("no channel for session %d", s
->self
);
2164 if(options
.hpn_disabled
)
2165 channel_set_fds(s
->chanid
,
2167 fderr
== -1 ? CHAN_EXTENDED_IGNORE
: CHAN_EXTENDED_READ
,
2168 1, is_tty
, CHAN_SES_WINDOW_DEFAULT
);
2170 channel_set_fds(s
->chanid
,
2172 fderr
== -1 ? CHAN_EXTENDED_IGNORE
: CHAN_EXTENDED_READ
,
2173 1, is_tty
, options
.hpn_buffer_size
);
2177 * Function to perform pty cleanup. Also called if we get aborted abnormally
2178 * (e.g., due to a dropped connection).
2181 session_pty_cleanup2(Session
*s
)
2184 error("session_pty_cleanup: no session");
2190 debug("session_pty_cleanup: session %d release %s", s
->self
, s
->tty
);
2192 /* Record that the user has logged out. */
2194 record_logout(s
->pid
, s
->tty
);
2196 /* Release the pseudo-tty. */
2198 pty_release(s
->tty
);
2201 * Close the server side of the socket pairs. We must do this after
2202 * the pty cleanup, so that another process doesn't get this pty
2203 * while we're still cleaning up.
2205 if (s
->ptymaster
!= -1 && close(s
->ptymaster
) < 0)
2206 error("close(s->ptymaster/%d): %s",
2207 s
->ptymaster
, strerror(errno
));
2209 /* unlink pty from session */
2214 session_pty_cleanup(Session
*s
)
2216 PRIVSEP(session_pty_cleanup2(s
));
2222 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2237 return "SIG@openssh.com";
2241 session_close_x11(int id
)
2245 if ((c
= channel_by_id(id
)) == NULL
) {
2246 debug("session_close_x11: x11 channel %d missing", id
);
2248 /* Detach X11 listener */
2249 debug("session_close_x11: detach x11 channel %d", id
);
2250 channel_cancel_cleanup(id
);
2251 if (c
->ostate
!= CHAN_OUTPUT_CLOSED
)
2257 session_close_single_x11(int id
, void *arg
)
2262 debug3("session_close_single_x11: channel %d", id
);
2263 channel_cancel_cleanup(id
);
2264 if ((s
= session_by_x11_channel(id
)) == NULL
)
2265 fatal("session_close_single_x11: no x11 channel %d", id
);
2266 for (i
= 0; s
->x11_chanids
[i
] != -1; i
++) {
2267 debug("session_close_single_x11: session %d: "
2268 "closing channel %d", s
->self
, s
->x11_chanids
[i
]);
2270 * The channel "id" is already closing, but make sure we
2271 * close all of its siblings.
2273 if (s
->x11_chanids
[i
] != id
)
2274 session_close_x11(s
->x11_chanids
[i
]);
2276 xfree(s
->x11_chanids
);
2277 s
->x11_chanids
= NULL
;
2282 if (s
->auth_proto
) {
2283 xfree(s
->auth_proto
);
2284 s
->auth_proto
= NULL
;
2287 xfree(s
->auth_data
);
2288 s
->auth_data
= NULL
;
2290 if (s
->auth_display
) {
2291 xfree(s
->auth_display
);
2292 s
->auth_display
= NULL
;
2297 session_exit_message(Session
*s
, int status
)
2301 if ((c
= channel_lookup(s
->chanid
)) == NULL
)
2302 fatal("session_exit_message: session %d: no channel %d",
2303 s
->self
, s
->chanid
);
2304 debug("session_exit_message: session %d channel %d pid %ld",
2305 s
->self
, s
->chanid
, (long)s
->pid
);
2307 if (WIFEXITED(status
)) {
2308 channel_request_start(s
->chanid
, "exit-status", 0);
2309 packet_put_int(WEXITSTATUS(status
));
2311 } else if (WIFSIGNALED(status
)) {
2312 channel_request_start(s
->chanid
, "exit-signal", 0);
2313 packet_put_cstring(sig2name(WTERMSIG(status
)));
2314 packet_put_char(WCOREDUMP(status
)? 1 : 0);
2315 packet_put_cstring("");
2316 packet_put_cstring("");
2319 /* Some weird exit cause. Just exit. */
2320 packet_disconnect("wait returned status %04x.", status
);
2323 /* disconnect channel */
2324 debug("session_exit_message: release channel %d", s
->chanid
);
2327 * Adjust cleanup callback attachment to send close messages when
2328 * the channel gets EOF. The session will be then be closed
2329 * by session_close_by_channel when the childs close their fds.
2331 channel_register_cleanup(c
->self
, session_close_by_channel
, 1);
2334 * emulate a write failure with 'chan_write_failed', nobody will be
2335 * interested in data we write.
2336 * Note that we must not call 'chan_read_failed', since there could
2337 * be some more data waiting in the pipe.
2339 if (c
->ostate
!= CHAN_OUTPUT_CLOSED
)
2340 chan_write_failed(c
);
2344 session_close(Session
*s
)
2348 debug("session_close: session %d pid %ld", s
->self
, (long)s
->pid
);
2350 session_pty_cleanup(s
);
2356 xfree(s
->x11_chanids
);
2357 if (s
->auth_display
)
2358 xfree(s
->auth_display
);
2360 xfree(s
->auth_data
);
2362 xfree(s
->auth_proto
);
2363 if (s
->env
!= NULL
) {
2364 for (i
= 0; i
< s
->num_env
; i
++) {
2365 xfree(s
->env
[i
].name
);
2366 xfree(s
->env
[i
].val
);
2370 session_proctitle(s
);
2371 session_unused(s
->self
);
2375 session_close_by_pid(pid_t pid
, int status
)
2377 Session
*s
= session_by_pid(pid
);
2379 debug("session_close_by_pid: no session for pid %ld",
2383 if (s
->chanid
!= -1)
2384 session_exit_message(s
, status
);
2386 session_pty_cleanup(s
);
2391 * this is called when a channel dies before
2392 * the session 'child' itself dies
2395 session_close_by_channel(int id
, void *arg
)
2397 Session
*s
= session_by_channel(id
);
2401 debug("session_close_by_channel: no session for id %d", id
);
2404 debug("session_close_by_channel: channel %d child %ld",
2407 debug("session_close_by_channel: channel %d: has child", id
);
2409 * delay detach of session, but release pty, since
2410 * the fd's to the child are already closed
2413 session_pty_cleanup(s
);
2416 /* detach by removing callback */
2417 channel_cancel_cleanup(s
->chanid
);
2419 /* Close any X11 listeners associated with this session */
2420 if (s
->x11_chanids
!= NULL
) {
2421 for (i
= 0; s
->x11_chanids
[i
] != -1; i
++) {
2422 session_close_x11(s
->x11_chanids
[i
]);
2423 s
->x11_chanids
[i
] = -1;
2432 session_destroy_all(void (*closefunc
)(Session
*))
2435 for (i
= 0; i
< sessions_nalloc
; i
++) {
2436 Session
*s
= &sessions
[i
];
2438 if (closefunc
!= NULL
)
2447 session_tty_list(void)
2449 static char buf
[1024];
2452 for (i
= 0; i
< sessions_nalloc
; i
++) {
2453 Session
*s
= &sessions
[i
];
2454 if (s
->used
&& s
->ttyfd
!= -1) {
2457 strlcat(buf
, ",", sizeof buf
);
2458 if ((p
= strstr(s
->tty
, "/pts/")) != NULL
)
2461 if ((p
= strrchr(s
->tty
, '/')) != NULL
)
2466 strlcat(buf
, p
, sizeof buf
);
2470 strlcpy(buf
, "notty", sizeof buf
);
2475 session_proctitle(Session
*s
)
2478 error("no user for session %d", s
->self
);
2480 setproctitle("%s@%s", s
->pw
->pw_name
, session_tty_list());
2484 session_setup_x11fwd(Session
*s
)
2487 char display
[512], auth_display
[512];
2488 char hostname
[MAXHOSTNAMELEN
];
2491 if (no_x11_forwarding_flag
) {
2492 packet_send_debug("X11 forwarding disabled in user configuration file.");
2495 if (!options
.x11_forwarding
) {
2496 debug("X11 forwarding disabled in server configuration file.");
2499 if (!options
.xauth_location
||
2500 (stat(options
.xauth_location
, &st
) == -1)) {
2501 packet_send_debug("No xauth program; cannot forward with spoofing.");
2504 if (options
.use_login
) {
2505 packet_send_debug("X11 forwarding disabled; "
2506 "not compatible with UseLogin=yes.");
2509 if (s
->display
!= NULL
) {
2510 debug("X11 display already set.");
2513 if (x11_create_display_inet(options
.x11_display_offset
,
2514 options
.x11_use_localhost
, s
->single_connection
,
2515 &s
->display_number
, &s
->x11_chanids
) == -1) {
2516 debug("x11_create_display_inet failed.");
2519 for (i
= 0; s
->x11_chanids
[i
] != -1; i
++) {
2520 channel_register_cleanup(s
->x11_chanids
[i
],
2521 session_close_single_x11
, 0);
2524 /* Set up a suitable value for the DISPLAY variable. */
2525 if (gethostname(hostname
, sizeof(hostname
)) < 0)
2526 fatal("gethostname: %.100s", strerror(errno
));
2528 * auth_display must be used as the displayname when the
2529 * authorization entry is added with xauth(1). This will be
2530 * different than the DISPLAY string for localhost displays.
2532 if (options
.x11_use_localhost
) {
2533 snprintf(display
, sizeof display
, "localhost:%u.%u",
2534 s
->display_number
, s
->screen
);
2535 snprintf(auth_display
, sizeof auth_display
, "unix:%u.%u",
2536 s
->display_number
, s
->screen
);
2537 s
->display
= xstrdup(display
);
2538 s
->auth_display
= xstrdup(auth_display
);
2540 snprintf(display
, sizeof display
, "%.400s:%u.%u", hostname
,
2541 s
->display_number
, s
->screen
);
2542 s
->display
= xstrdup(display
);
2543 s
->auth_display
= xstrdup(display
);
2550 do_authenticated2(Authctxt
*authctxt
)
2552 server_loop2(authctxt
);
2556 do_cleanup(Authctxt
*authctxt
)
2558 static int called
= 0;
2560 debug("do_cleanup");
2562 /* no cleanup if we're in the child for login shell */
2566 /* avoid double cleanup */
2571 if (authctxt
== NULL
|| !authctxt
->authenticated
)
2574 if (options
.kerberos_ticket_cleanup
)
2575 krb4_cleanup_proc(authctxt
);
2578 if (options
.kerberos_ticket_cleanup
&&
2580 krb5_cleanup_proc(authctxt
);
2584 if (compat20
&& options
.gss_cleanup_creds
)
2585 ssh_gssapi_cleanup_creds();
2589 if (options
.use_pam
) {
2591 sshpam_thread_cleanup();
2595 /* remove agent socket */
2596 auth_sock_cleanup_proc(authctxt
->pw
);
2599 * Cleanup ptys/utmp only if privsep is disabled,
2600 * or if running in monitor.
2602 if (!use_privsep
|| mm_is_monitor())
2603 session_destroy_all(session_pty_cleanup2
);