ssh has moved
[netbsd-mini2440.git] / crypto / dist / ssh / session.c
blob8bfaf2241e9372da3d47721947ebc55fc121fe0d
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 $ */
3 /*
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
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
18 * are met:
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.
37 #include "includes.h"
38 __RCSID("$NetBSD: session.c,v 1.48 2008/06/22 15:42:50 christos Exp $");
39 #include <sys/types.h>
40 #include <sys/wait.h>
41 #include <sys/un.h>
42 #include <sys/stat.h>
43 #include <sys/socket.h>
44 #include <sys/param.h>
45 #include <sys/queue.h>
47 #include <errno.h>
48 #include <grp.h>
49 #include <login_cap.h>
50 #include <paths.h>
51 #include <pwd.h>
52 #include <signal.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
58 #include "xmalloc.h"
59 #include "ssh.h"
60 #include "ssh1.h"
61 #include "ssh2.h"
62 #include "sshpty.h"
63 #include "packet.h"
64 #include "buffer.h"
65 #include "match.h"
66 #include "uidswap.h"
67 #include "compat.h"
68 #include "channels.h"
69 #include "key.h"
70 #include "cipher.h"
71 #include "kex.h"
72 #include "hostfile.h"
73 #include "auth.h"
74 #include "auth-options.h"
75 #include "pathnames.h"
76 #include "log.h"
77 #include "servconf.h"
78 #include "sshlogin.h"
79 #include "serverloop.h"
80 #include "canohost.h"
81 #include "misc.h"
82 #include "session.h"
83 #ifdef GSSAPI
84 #include "ssh-gss.h"
85 #endif
86 #include "monitor_wrap.h"
87 #include "sftp.h"
89 #ifdef KRB5
90 #include <kafs.h>
91 #endif
93 /* func */
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 *);
105 void do_motd(void);
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 *);
113 /* import */
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;
126 /* data */
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
136 login_cap_t *lc;
137 #endif
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 */
147 static void
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;
155 restore_uid();
159 static int
160 auth_input_request_forwarding(struct passwd * pw)
162 Channel *nc;
163 int sock = -1;
164 struct sockaddr_un sunaddr;
166 if (auth_sock_name != NULL) {
167 error("authentication forwarding requested twice.");
168 return 0;
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));
181 restore_uid();
182 xfree(auth_sock_dir);
183 auth_sock_dir = NULL;
184 goto authsock_err;
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);
192 if (sock < 0) {
193 error("socket: %.100s", strerror(errno));
194 restore_uid();
195 goto authsock_err;
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));
205 restore_uid();
206 goto authsock_err;
209 /* Restore the privileged uid. */
210 restore_uid();
212 /* Start listening on the socket. */
213 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
214 error("listen: %.100s", strerror(errno));
215 goto authsock_err;
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));
225 return 1;
227 authsock_err:
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);
234 if (sock != -1)
235 close(sock);
236 auth_sock_name = NULL;
237 auth_sock_dir = NULL;
238 return 0;
241 static void
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);
251 void
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();
260 if (compat20)
261 do_authenticated2(authctxt);
262 else
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.
274 static void
275 do_authenticated1(Authctxt *authctxt)
277 Session *s;
278 char *command;
279 int success, type, screen_flag;
280 int enable_compression_after_reply = 0;
281 u_int proto_len, data_len, dlen, compression_level = 0;
283 s = session_new();
284 if (s == NULL) {
285 error("no more sessions");
286 return;
288 s->authctxt = authctxt;
289 s->pw = authctxt->pw;
292 * We stay in this loop until the client requests to execute a shell
293 * or a command.
295 for (;;) {
296 success = 0;
298 /* Get a packet from the client. */
299 type = packet_read();
301 /* Process the packet. */
302 switch (type) {
303 case SSH_CMSG_REQUEST_COMPRESSION:
304 compression_level = packet_get_int();
305 packet_check_eom();
306 if (compression_level < 1 || compression_level > 9) {
307 packet_send_debug("Received invalid compression level %d.",
308 compression_level);
309 break;
311 if (options.compression == COMP_NONE) {
312 debug2("compression disabled");
313 break;
315 /* Enable compression after we have responded with SUCCESS. */
316 enable_compression_after_reply = 1;
317 success = 1;
318 break;
320 case SSH_CMSG_REQUEST_PTY:
321 success = session_pty_req(s);
322 break;
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) {
333 if (!screen_flag)
334 debug2("Buggy client: "
335 "X11 screen flag missing");
336 s->screen = packet_get_int();
337 } else {
338 s->screen = 0;
340 packet_check_eom();
341 success = session_setup_x11fwd(s);
342 if (!success) {
343 xfree(s->auth_proto);
344 xfree(s->auth_data);
345 s->auth_proto = NULL;
346 s->auth_data = NULL;
348 break;
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.");
354 break;
356 debug("Received authentication agent forwarding request.");
357 success = auth_input_request_forwarding(s->pw);
358 break;
360 case SSH_CMSG_PORT_FORWARD_REQUEST:
361 if (no_port_forwarding_flag) {
362 debug("Port forwarding not permitted for this authentication.");
363 break;
365 if (!options.allow_tcp_forwarding) {
366 debug("Port forwarding not permitted.");
367 break;
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.");
373 break;
375 success = 1;
376 break;
378 case SSH_CMSG_MAX_PACKET_SIZE:
379 if (packet_set_maxsize(packet_get_int()) > 0)
380 success = 1;
381 break;
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.");
387 } else {
388 char *kdata = packet_get_string(&dlen);
389 packet_check_eom();
391 /* XXX - 0x41, see creds_to_radix version */
392 if (kdata[0] != 0x41) {
393 #ifdef KRB5
394 krb5_data tgt;
395 tgt.data = kdata;
396 tgt.length = dlen;
398 if (auth_krb5_tgt(s->authctxt, &tgt))
399 success = 1;
400 else
401 verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
402 #endif /* KRB5 */
403 } else {
404 #ifdef AFS
405 if (auth_krb4_tgt(s->authctxt, kdata))
406 success = 1;
407 else
408 verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
409 #endif /* AFS */
411 xfree(kdata);
413 break;
414 #endif /* AFS || KRB5 */
416 #ifdef AFS
417 case SSH_CMSG_HAVE_AFS_TOKEN:
418 if (!options.afs_token_passing || !k_hasafs()) {
419 verbose("AFS token passing disabled.");
420 } else {
421 /* Accept AFS token. */
422 char *token = packet_get_string(&dlen);
423 packet_check_eom();
425 if (auth_afs_token(s->authctxt, token))
426 success = 1;
427 else
428 verbose("AFS token refused for %.100s",
429 s->authctxt->user);
430 xfree(token);
432 break;
433 #endif /* AFS */
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)
441 packet_disconnect(
442 "command execution failed");
443 xfree(command);
444 } else {
445 if (do_exec(s, NULL) != 0)
446 packet_disconnect(
447 "shell execution failed");
449 packet_check_eom();
450 session_close(s);
451 return;
453 default:
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);
461 packet_send();
462 packet_write_wait();
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);
472 #define USE_PIPES
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)
481 pid_t pid;
482 #ifdef USE_PIPES
483 int pin[2], pout[2], perr[2];
485 /* Allocate pipes for communicating with the program. */
486 if (pipe(pin) < 0) {
487 error("%s: pipe in: %.100s", __func__, strerror(errno));
488 return -1;
490 if (pipe(pout) < 0) {
491 error("%s: pipe out: %.100s", __func__, strerror(errno));
492 close(pin[0]);
493 close(pin[1]);
494 return -1;
496 if (pipe(perr) < 0) {
497 error("%s: pipe err: %.100s", __func__, strerror(errno));
498 close(pin[0]);
499 close(pin[1]);
500 close(pout[0]);
501 close(pout[1]);
502 return -1;
504 #else
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));
510 return -1;
512 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) {
513 error("%s: socketpair #2: %.100s", __func__, strerror(errno));
514 close(inout[0]);
515 close(inout[1]);
516 return -1;
518 #endif
520 if (s == NULL)
521 fatal("do_exec_no_pty: no session");
523 session_proctitle(s);
525 #ifdef notdef
526 #if defined(USE_PAM)
527 if (options.use_pam && !use_privsep)
528 do_pam_setcred(1);
529 #endif /* USE_PAM */
530 #endif
532 /* Fork the child. */
533 switch ((pid = fork())) {
534 case -1:
535 error("%s: fork: %.100s", __func__, strerror(errno));
536 #ifdef USE_PIPES
537 close(pin[0]);
538 close(pin[1]);
539 close(pout[0]);
540 close(pout[1]);
541 close(perr[0]);
542 close(perr[1]);
543 #else
544 close(inout[0]);
545 close(inout[1]);
546 close(err[0]);
547 close(err[1]);
548 #endif
549 return -1;
550 case 0:
551 is_child = 1;
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.
561 if (setsid() < 0)
562 error("setsid failed: %.100s", strerror(errno));
564 #ifdef USE_PIPES
566 * Redirect stdin. We close the parent side of the socket
567 * pair, and make the child side the standard input.
569 close(pin[1]);
570 if (dup2(pin[0], 0) < 0)
571 perror("dup2 stdin");
572 close(pin[0]);
574 /* Redirect stdout. */
575 close(pout[0]);
576 if (dup2(pout[1], 1) < 0)
577 perror("dup2 stdout");
578 close(pout[1]);
580 /* Redirect stderr. */
581 close(perr[0]);
582 if (dup2(perr[1], 2) < 0)
583 perror("dup2 stderr");
584 close(perr[1]);
585 #else
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.
591 close(inout[1]);
592 close(err[1]);
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");
597 close(inout[0]);
598 if (dup2(err[0], 2) < 0) /* stderr */
599 perror("dup2 stderr");
600 close(err[0]);
601 #endif
603 /* Do processing for the child (exec command etc). */
604 do_child(s, command);
605 /* NOTREACHED */
606 default:
607 break;
610 s->pid = pid;
611 /* Set interactive/non-interactive mode. */
612 packet_set_interactive(s->display != NULL);
614 #ifdef USE_PIPES
615 /* We are the parent. Close the child sides of the pipes. */
616 close(pin[0]);
617 close(pout[1]);
618 close(perr[1]);
620 if (compat20) {
621 if (s->is_subsystem) {
622 close(perr[0]);
623 perr[0] = -1;
625 session_set_fds(s, pin[1], pout[0], perr[0], 0);
626 } else {
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]. */
631 #else
632 /* We are the parent. Close the child sides of the socket pairs. */
633 close(inout[0]);
634 close(err[0]);
637 * Enter the interactive session. Note: server_loop must be able to
638 * handle the case that fdin and fdout are the same.
640 if (compat20) {
641 session_set_fds(s, inout[1], inout[1],
642 s->is_subsystem ? -1 : err[1], 0);
643 if (s->is_subsystem)
644 close(err[1]);
645 } else {
646 server_loop(pid, inout[1], inout[1], err[1]);
647 /* server_loop has closed inout[1] and err[1]. */
649 #endif
650 return 0;
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;
663 pid_t pid;
665 if (s == NULL)
666 fatal("do_exec_pty: no session");
667 ptyfd = s->ptyfd;
668 ttyfd = s->ttyfd;
670 #if defined(USE_PAM)
671 if (options.use_pam) {
672 do_pam_set_tty(s->tty);
673 if (!use_privsep)
674 do_pam_setcred(1);
676 #endif
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));
687 close(ttyfd);
688 close(ptyfd);
689 return -1;
691 /* we keep a reference to the pty master */
692 if ((ptymaster = dup(ptyfd)) < 0) {
693 error("%s: dup #2: %s", __func__, strerror(errno));
694 close(ttyfd);
695 close(ptyfd);
696 close(fdout);
697 return -1;
700 /* Fork the child. */
701 switch ((pid = fork())) {
702 case -1:
703 error("%s: fork: %.100s", __func__, strerror(errno));
704 close(fdout);
705 close(ptymaster);
706 close(ttyfd);
707 close(ptyfd);
708 return -1;
709 case 0:
710 is_child = 1;
712 close(fdout);
713 close(ptymaster);
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. */
719 close(ptyfd);
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. */
733 close(ttyfd);
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
741 * the command.
743 do_child(s, command);
744 /* NOTREACHED */
745 default:
746 break;
748 s->pid = pid;
750 /* Parent. Close the slave side of the pseudo tty. */
751 close(ttyfd);
753 /* Enter interactive session. */
754 s->ptymaster = ptymaster;
755 packet_set_interactive(1);
756 if (compat20) {
757 session_set_fds(s, ptyfd, fdout, -1, 1);
758 } else {
759 server_loop(pid, ptyfd, fdout, -1);
760 /* server_loop _has_ closed ptyfd and fdout. */
762 return 0;
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)
772 int ret;
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);
792 #ifdef GSSAPI
793 if (options.gss_authentication) {
794 temporarily_use_uid(s->pw);
795 ssh_gssapi_storecreds();
796 restore_uid();
798 #endif
799 if (s->ttyfd != -1)
800 ret = do_exec_pty(s, command);
801 else
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);
813 return ret;
817 /* administrative, login(1)-like work */
818 void
819 do_login(Session *s, const char *command)
821 socklen_t fromlen;
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));
836 cleanup_exit(255);
840 /* Record that there was a login on that tty from the remote host. */
841 if (!use_privsep)
842 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
843 get_remote_name_or_ip(utmp_len,
844 options.use_dns),
845 (struct sockaddr *)&from, fromlen);
847 #ifdef USE_PAM
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) {
853 display_loginmsg();
854 do_pam_chauthtok();
855 s->authctxt->force_pwchange = 0;
856 /* XXX - signal [net] parent to enable forwardings */
858 #endif
860 if (check_quietlogin(s, command))
861 return;
863 display_loginmsg();
865 do_motd();
869 * Display the message of the day.
871 void
872 do_motd(void)
874 FILE *f;
875 char buf[256];
877 if (options.print_motd) {
878 #ifdef HAVE_LOGIN_CAP
879 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
880 "/etc/motd"), "r");
881 #else
882 f = fopen("/etc/motd", "r");
883 #endif
884 if (f) {
885 while (fgets(buf, sizeof(buf), f))
886 fputs(buf, stdout);
887 fclose(f);
894 * Check for quiet login, either .hushlogin or command given.
897 check_quietlogin(Session *s, const char *command)
899 char buf[256];
900 struct passwd *pw = s->pw;
901 struct stat st;
903 /* Return 1 if .hushlogin exists or a command given. */
904 if (command != NULL)
905 return 1;
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)
909 return 1;
910 #else
911 if (stat(buf, &st) >= 0)
912 return 1;
913 #endif
914 return 0;
918 * Sets the value of the given variable in the environment. If the variable
919 * already exists, its value is overriden.
921 void
922 child_set_env(char ***envp, u_int *envsizep, const char *name,
923 const char *value)
925 char **env;
926 u_int envsize;
927 u_int i, namelen;
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.
934 env = *envp;
935 namelen = strlen(name);
936 for (i = 0; env[i]; i++)
937 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
938 break;
939 if (env[i]) {
940 /* Reuse the slot. */
941 xfree(env[i]);
942 } else {
943 /* New variable. Expand if necessary. */
944 envsize = *envsizep;
945 if (i >= envsize - 1) {
946 if (envsize >= 1000)
947 fatal("child_set_env: too many env vars");
948 envsize += 50;
949 env = (*envp) = xrealloc(env, envsize, sizeof(char *));
950 *envsizep = envsize;
952 /* Need to set the NULL pointer at end of array beyond the new slot. */
953 env[i + 1] = NULL;
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.
964 * Taken from:
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.
968 static void
969 lc_setuserenv(char ***env, u_int *envsize, login_cap_t *lc)
971 const char *stop = ", \t";
972 int i, count;
973 char *ptr;
974 char **res;
975 char *str = login_getcapstr(lc, "setenv", NULL, NULL);
977 if (str == NULL || *str == '\0')
978 return;
980 /* count the sub-strings */
981 for (i = 1, ptr = str; *ptr; i++) {
982 ptr += strcspn(ptr, stop);
983 if (*ptr)
984 ptr++;
987 /* allocate ptr array and string */
988 count = i;
989 res = malloc(count * sizeof(char *) + strlen(str) + 1);
991 if (!res)
992 return;
994 ptr = (char *)res + count * sizeof(char *);
995 strcpy(ptr, str);
997 /* split string */
998 for (i = 0; *ptr && i < count; i++) {
999 res[i] = ptr;
1000 ptr += strcspn(ptr, stop);
1001 if (*ptr)
1002 *ptr++ = '\0';
1005 res[i] = NULL;
1007 for (i = 0; i < count && res[i]; i++) {
1008 if (*res[i] != '\0') {
1009 if ((ptr = strchr(res[i], '=')) != NULL)
1010 *ptr++ = '\0';
1011 else
1012 ptr = "";
1013 child_set_env(env, envsize, res[i], ptr);
1017 free(res);
1018 return;
1020 #endif
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.
1028 static void
1029 read_environment_file(char ***env, u_int *envsize,
1030 const char *filename)
1032 FILE *f;
1033 char buf[4096];
1034 char *cp, *value;
1035 u_int lineno = 0;
1037 f = fopen(filename, "r");
1038 if (!f)
1039 return;
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')
1047 continue;
1049 cp[strcspn(cp, "\n")] = '\0';
1051 value = strchr(cp, '=');
1052 if (value == NULL) {
1053 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
1054 filename);
1055 continue;
1058 * Replace the equals sign by nul, and advance value to
1059 * the value string.
1061 *value = '\0';
1062 value++;
1063 child_set_env(env, envsize, cp, value);
1065 fclose(f);
1068 #ifdef USE_PAM
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;
1073 int i;
1075 if (source == NULL)
1076 return;
1078 for(i = 0; source[i] != NULL; i++) {
1079 var_name = xstrdup(source[i]);
1080 if ((var_val = strstr(var_name, "=")) == NULL) {
1081 xfree(var_name);
1082 continue;
1084 *var_val++ = '\0';
1086 debug3("Copy environment: %s=%s", var_name, var_val);
1087 child_set_env(env, envsize, var_name, var_val);
1089 xfree(var_name);
1092 #endif
1094 static char **
1095 do_setup_env(Session *s, const char *shell)
1097 char buf[256];
1098 u_int i, envsize;
1099 char **env, *laddr;
1100 struct passwd *pw = s->pw;
1102 /* Initialize the environment. */
1103 envsize = 100;
1104 env = xcalloc(envsize, sizeof(char *));
1105 env[0] = NULL;
1107 #ifdef GSSAPI
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);
1112 #endif
1114 if (!options.use_login) {
1115 #ifdef HAVE_LOGIN_CAP
1116 lc_setuserenv(&env, &envsize, lc);
1117 #endif
1118 /* Set basic environment. */
1119 for (i = 0; i < s->num_env; i++)
1120 child_set_env(&env, &envsize, s->env[i].name,
1121 s->env[i].val);
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);
1129 else
1130 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1131 #else
1132 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1133 #endif
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);
1142 if (getenv("TZ"))
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;
1149 char *str = ce->s;
1151 for (i = 0; str[i] != '=' && str[i]; i++)
1153 if (str[i] == '=') {
1154 str[i] = 0;
1155 child_set_env(&env, &envsize, str, str + i + 1);
1157 custom_environment = ce->next;
1158 xfree(ce->s);
1159 xfree(ce);
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());
1171 xfree(laddr);
1172 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1174 if (s->ttyfd != -1)
1175 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1176 if (s->term)
1177 child_set_env(&env, &envsize, "TERM", s->term);
1178 if (s->display)
1179 child_set_env(&env, &envsize, "DISPLAY", s->display);
1180 if (original_command)
1181 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1182 original_command);
1183 #ifdef KRB4
1184 if (s->authctxt->krb4_ticket_file)
1185 child_set_env(&env, &envsize, "KRBTKFILE",
1186 s->authctxt->krb4_ticket_file);
1187 #endif
1188 #ifdef KRB5
1189 if (s->authctxt->krb5_ticket_file)
1190 child_set_env(&env, &envsize, "KRB5CCNAME",
1191 s->authctxt->krb5_ticket_file);
1192 #endif
1193 #ifdef USE_PAM
1195 * Pull in any environment variables that may have
1196 * been set by PAM.
1198 if (options.use_pam) {
1199 char **p;
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,
1213 auth_sock_name);
1215 /* read $HOME/.ssh/environment. */
1216 if (options.permit_user_env && !options.use_login) {
1217 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1218 pw->pw_dir);
1219 read_environment_file(&env, &envsize, buf);
1221 if (debug_flag) {
1222 /* dump the environment */
1223 fprintf(stderr, "Environment:\n");
1224 for (i = 0; env[i]; i++)
1225 fprintf(stderr, " %.200s\n", env[i]);
1227 return env;
1231 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1232 * first in this order).
1234 static void
1235 do_rc_files(Session *s, const char *shell)
1237 FILE *f = NULL;
1238 char cmd[1024];
1239 int do_xauth;
1240 struct stat st;
1242 do_xauth =
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);
1250 if (debug_flag)
1251 fprintf(stderr, "Running %s\n", cmd);
1252 f = popen(cmd, "w");
1253 if (f) {
1254 if (do_xauth)
1255 fprintf(f, "%s %s\n", s->auth_proto,
1256 s->auth_data);
1257 pclose(f);
1258 } else
1259 fprintf(stderr, "Could not run %s\n",
1260 _PATH_SSH_USER_RC);
1261 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1262 if (debug_flag)
1263 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1264 _PATH_SSH_SYSTEM_RC);
1265 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1266 if (f) {
1267 if (do_xauth)
1268 fprintf(f, "%s %s\n", s->auth_proto,
1269 s->auth_data);
1270 pclose(f);
1271 } else
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. */
1276 if (debug_flag) {
1277 fprintf(stderr,
1278 "Running %.500s remove %.100s\n",
1279 options.xauth_location, s->auth_display);
1280 fprintf(stderr,
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");
1288 if (f) {
1289 fprintf(f, "remove %s\n",
1290 s->auth_display);
1291 fprintf(f, "add %s %s %s\n",
1292 s->auth_display, s->auth_proto,
1293 s->auth_data);
1294 pclose(f);
1295 } else {
1296 fprintf(stderr, "Could not run %s\n",
1297 cmd);
1302 static void
1303 do_nologin(struct passwd *pw)
1305 FILE *f = NULL;
1306 char buf[1024];
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");
1312 #else
1313 if (pw->pw_uid)
1314 f = fopen(_PATH_NOLOGIN, "r");
1315 #endif
1316 if (f) {
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))
1321 fputs(buf, stderr);
1322 fclose(f);
1323 exit(254);
1328 * Chroot into a directory after checking it for safety: all path components
1329 * must be root-owned directories with strict permissions.
1331 static void
1332 safely_chroot(const char *path, uid_t uid)
1334 const char *cp;
1335 char component[MAXPATHLEN];
1336 struct stat st;
1338 if (*path != '/')
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));
1350 else {
1351 cp++;
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. */
1383 void
1384 do_setusercontext(struct passwd *pw)
1386 char *chroot_path, *tmp;
1388 if (getuid() == 0 || geteuid() == 0) {
1389 #ifdef HAVE_LOGIN_CAP
1390 # ifdef USE_PAM
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");
1399 exit(1);
1401 #else
1403 if (setlogin(pw->pw_name) < 0)
1404 error("setlogin failed: %s", strerror(errno));
1405 if (setgid(pw->pw_gid) < 0) {
1406 perror("setgid");
1407 exit(1);
1409 /* Initialize the group list. */
1410 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1411 perror("initgroups");
1412 exit(1);
1414 endgrent();
1415 # ifdef USE_PAM
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 */
1425 #endif
1426 if (options.chroot_directory != NULL &&
1427 strcasecmp(options.chroot_directory, "none") != 0) {
1428 tmp = tilde_expand_filename(options.chroot_directory,
1429 pw->pw_uid);
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);
1433 free(tmp);
1434 free(chroot_path);
1437 #ifdef HAVE_LOGIN_CAP
1438 /* Set UID */
1439 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1440 perror("unable to set user context (setuser)");
1441 exit(1);
1443 #else
1444 /* Permanently switch to the desired uid. */
1445 permanently_set_uid(pw);
1446 #endif
1448 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1449 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1452 static void
1453 do_pwchange(Session *s)
1455 fflush(NULL);
1456 fprintf(stderr, "WARNING: Your password has expired.\n");
1457 if (s->ttyfd != -1) {
1458 fprintf(stderr,
1459 "You must change your password now and login again!\n");
1460 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1461 perror("passwd");
1462 } else {
1463 fprintf(stderr,
1464 "Password change required but no TTY available.\n");
1466 exit(1);
1469 static void
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. */
1479 perror("login");
1480 exit(1);
1483 static void
1484 child_close_fds(void)
1486 int i;
1488 if (packet_get_connection_in() == packet_get_connection_out())
1489 close(packet_get_connection_in());
1490 else {
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.
1505 endpwent();
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
1511 * descriptors open.
1513 for (i = 3; i < 64; i++)
1514 close(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.
1522 #define ARGV_MAX 10
1523 void
1524 do_child(Session *s, const char *command)
1526 extern char **environ;
1527 char **env;
1528 char *argv[ARGV_MAX];
1529 const char *shell, *shell0, *hostname = NULL;
1530 struct passwd *pw = s->pw;
1531 int r = 0;
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);
1539 child_close_fds();
1540 do_pwchange(s);
1541 exit(1);
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) {
1553 do_nologin(pw);
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))
1561 display_loginmsg();
1563 #ifdef USE_PAM
1564 if (options.use_pam && !is_pam_session_open()) {
1565 debug3("PAM session not opened, exiting");
1566 display_loginmsg();
1567 exit(254);
1569 #endif
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);
1585 #endif
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,
1590 options.use_dns);
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.
1598 child_close_fds();
1601 * Must take new environment into use so that .ssh/rc,
1602 * /etc/ssh/sshrc and xauth are run in the proper environment.
1604 environ = env;
1606 #ifdef KRB5
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)) {
1617 char cell[64];
1619 debug("Getting AFS token");
1621 k_setpag();
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);
1630 #endif
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,
1639 strerror(errno));
1640 if (r)
1641 exit(1);
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;
1654 int i;
1655 char *p, *args;
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)
1661 argv[i++] = p;
1662 argv[i] = NULL;
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);
1670 /* NEVERREACHED */
1673 /* Get the last component of the shell name. */
1674 if ((shell0 = strrchr(shell, '/')) != NULL)
1675 shell0++;
1676 else
1677 shell0 = shell;
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.
1684 if (!command) {
1685 char argv0[256];
1687 /* Start the shell. Set initial character to '-'. */
1688 argv0[0] = '-';
1690 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1691 >= sizeof(argv0) - 1) {
1692 errno = EINVAL;
1693 perror(shell);
1694 exit(1);
1697 /* Execute the shell. */
1698 argv[0] = argv0;
1699 argv[1] = NULL;
1700 execve(shell, argv, env);
1702 /* Executing the shell failed. */
1703 perror(shell);
1704 exit(1);
1707 * Execute the command using the user's shell. This uses the -c
1708 * option to execute the command.
1710 argv[0] = (char *) shell0;
1711 argv[1] = "-c";
1712 argv[2] = (char *) command;
1713 argv[3] = NULL;
1714 execve(shell, argv, env);
1715 perror(shell);
1716 exit(1);
1719 void
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;
1740 Session *
1741 session_new(void)
1743 Session *s, *tmp;
1745 if (sessions_first_unused == -1) {
1746 if (sessions_nalloc >= options.max_sessions)
1747 return NULL;
1748 debug2("%s: allocate (allocated %d max %d)",
1749 __func__, sessions_nalloc, options.max_sessions);
1750 tmp = xrealloc(sessions, sessions_nalloc + 1,
1751 sizeof(*sessions));
1752 if (tmp == NULL) {
1753 error("%s: cannot allocate %d sessions",
1754 __func__, sessions_nalloc + 1);
1755 return NULL;
1757 sessions = tmp;
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,
1765 sessions_nalloc);
1768 s = &sessions[sessions_first_unused];
1769 if (s->used) {
1770 fatal("%s: session %d already used",
1771 __func__, sessions_first_unused);
1773 sessions_first_unused = s->next_unused;
1774 s->used = 1;
1775 s->next_unused = -1;
1776 debug("session_new: session %d", s->self);
1778 return s;
1781 static void
1782 session_dump(void)
1784 int i;
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",
1790 s->used,
1791 s->next_unused,
1792 s->self,
1794 s->chanid,
1795 (long)s->pid);
1800 session_open(Authctxt *authctxt, int chanid)
1802 Session *s = session_new();
1803 debug("session_open: channel %d", chanid);
1804 if (s == NULL) {
1805 error("no more sessions");
1806 return 0;
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);
1813 s->chanid = chanid;
1814 return 1;
1817 Session *
1818 session_by_tty(char *tty)
1820 int i;
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);
1825 return s;
1828 debug("session_by_tty: unknown tty %.100s", tty);
1829 session_dump();
1830 return NULL;
1833 static Session *
1834 session_by_channel(int id)
1836 int i;
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",
1841 i, id);
1842 return s;
1845 debug("session_by_channel: unknown channel %d", id);
1846 session_dump();
1847 return NULL;
1850 static Session *
1851 session_by_x11_channel(int id)
1853 int i, j;
1855 for (i = 0; i < sessions_nalloc; i++) {
1856 Session *s = &sessions[i];
1858 if (s->x11_chanids == NULL || !s->used)
1859 continue;
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);
1864 return s;
1868 debug("session_by_x11_channel: unknown channel %d", id);
1869 session_dump();
1870 return NULL;
1873 static Session *
1874 session_by_pid(pid_t pid)
1876 int i;
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)
1881 return s;
1883 error("session_by_pid: unknown pid %ld", (long)pid);
1884 session_dump();
1885 return NULL;
1888 static int
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();
1895 packet_check_eom();
1896 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1897 return 1;
1900 static int
1901 session_pty_req(Session *s)
1903 u_int len;
1904 int n_bytes;
1906 if (no_pty_flag) {
1907 debug("Allocating a pty not permitted for this authentication.");
1908 return 0;
1910 if (s->ttyfd != -1) {
1911 packet_disconnect("Protocol error: you already have a pty.");
1912 return 0;
1915 s->term = packet_get_string(&len);
1917 if (compat20) {
1918 s->col = packet_get_int();
1919 s->row = packet_get_int();
1920 } else {
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) {
1928 xfree(s->term);
1929 s->term = NULL;
1932 /* Allocate a pty and open it. */
1933 debug("Allocating pty.");
1934 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
1935 sizeof(s->tty)))) {
1936 if (s->term)
1937 xfree(s->term);
1938 s->term = NULL;
1939 s->ptyfd = -1;
1940 s->ttyfd = -1;
1941 error("session_pty_req: session %d alloc failed", s->self);
1942 return 0;
1944 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1946 /* for SSH1 the tty modes length is not given */
1947 if (!compat20)
1948 n_bytes = packet_remaining();
1949 tty_parse_modes(s->ttyfd, &n_bytes);
1951 if (!use_privsep)
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);
1957 packet_check_eom();
1958 session_proctitle(s);
1959 return 1;
1962 static int
1963 session_subsystem_req(Session *s)
1965 struct stat st;
1966 u_int len;
1967 int success = 0;
1968 char *prog, *cmd, *subsys = packet_get_string(&len);
1969 u_int i;
1971 packet_check_eom();
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,
1982 strerror(errno));
1983 break;
1984 } else {
1985 s->is_subsystem = SUBSYSTEM_EXT;
1987 debug("subsystem: exec() %s", cmd);
1988 success = do_exec(s, cmd) == 0;
1989 break;
1993 if (!success)
1994 logit("subsystem request for %.100s failed, subsystem not found",
1995 subsys);
1997 xfree(subsys);
1998 return success;
2001 static int
2002 session_x11_req(Session *s)
2004 int success;
2006 if (s->auth_proto != NULL || s->auth_data != NULL) {
2007 error("session_x11_req: session %d: "
2008 "x11 forwarding already active", s->self);
2009 return 0;
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();
2015 packet_check_eom();
2017 success = session_setup_x11fwd(s);
2018 if (!success) {
2019 xfree(s->auth_proto);
2020 xfree(s->auth_data);
2021 s->auth_proto = NULL;
2022 s->auth_data = NULL;
2024 return success;
2027 static int
2028 session_shell_req(Session *s)
2030 packet_check_eom();
2031 return do_exec(s, NULL) == 0;
2034 static int
2035 session_exec_req(Session *s)
2037 u_int len, success;
2039 char *command = packet_get_string(&len);
2040 packet_check_eom();
2041 success = do_exec(s, command) == 0;
2042 xfree(command);
2043 return success;
2046 static int
2047 session_break_req(Session *s)
2050 packet_get_int(); /* ignored */
2051 packet_check_eom();
2053 if (s->ttyfd == -1 || tcsendbreak(s->ttyfd, 0) < 0)
2054 return 0;
2055 return 1;
2058 static int
2059 session_env_req(Session *s)
2061 char *name, *val;
2062 u_int name_len, val_len, i;
2064 name = packet_get_string(&name_len);
2065 val = packet_get_string(&val_len);
2066 packet_check_eom();
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);
2071 goto fail;
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,
2078 sizeof(*s->env));
2079 s->env[s->num_env].name = name;
2080 s->env[s->num_env].val = val;
2081 s->num_env++;
2082 return (1);
2085 debug2("Ignoring env request %s: disallowed name", name);
2087 fail:
2088 xfree(name);
2089 xfree(val);
2090 return (0);
2093 static int
2094 session_auth_agent_req(Session *s)
2096 static int called = 0;
2097 packet_check_eom();
2098 if (no_agent_forwarding_flag || !options.allow_agent_forwarding) {
2099 debug("session_auth_agent_req: no_agent_forwarding_flag");
2100 return 0;
2102 if (called) {
2103 return 0;
2104 } else {
2105 called = 1;
2106 return auth_input_request_forwarding(s->pw);
2111 session_input_channel_req(Channel *c, const char *rtype)
2113 int success = 0;
2114 Session *s;
2116 if ((s = session_by_channel(c->self)) == NULL) {
2117 logit("session_input_channel_req: no session %d req %.100s",
2118 c->self, rtype);
2119 return 0;
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);
2150 return success;
2153 void
2154 session_set_fds(Session *s, int fdin, int fdout, int fderr, int is_tty)
2156 if (!compat20)
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,
2166 fdout, fdin, fderr,
2167 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2168 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2169 else
2170 channel_set_fds(s->chanid,
2171 fdout, fdin, fderr,
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).
2180 void
2181 session_pty_cleanup2(Session *s)
2183 if (s == NULL) {
2184 error("session_pty_cleanup: no session");
2185 return;
2187 if (s->ttyfd == -1)
2188 return;
2190 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2192 /* Record that the user has logged out. */
2193 if (s->pid != 0)
2194 record_logout(s->pid, s->tty);
2196 /* Release the pseudo-tty. */
2197 if (getuid() == 0)
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 */
2210 s->ttyfd = -1;
2213 void
2214 session_pty_cleanup(Session *s)
2216 PRIVSEP(session_pty_cleanup2(s));
2219 static char *
2220 sig2name(int sig)
2222 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2223 SSH_SIG(ABRT);
2224 SSH_SIG(ALRM);
2225 SSH_SIG(FPE);
2226 SSH_SIG(HUP);
2227 SSH_SIG(ILL);
2228 SSH_SIG(INT);
2229 SSH_SIG(KILL);
2230 SSH_SIG(PIPE);
2231 SSH_SIG(QUIT);
2232 SSH_SIG(SEGV);
2233 SSH_SIG(TERM);
2234 SSH_SIG(USR1);
2235 SSH_SIG(USR2);
2236 #undef SSH_SIG
2237 return "SIG@openssh.com";
2240 static void
2241 session_close_x11(int id)
2243 Channel *c;
2245 if ((c = channel_by_id(id)) == NULL) {
2246 debug("session_close_x11: x11 channel %d missing", id);
2247 } else {
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)
2252 chan_mark_dead(c);
2256 static void
2257 session_close_single_x11(int id, void *arg)
2259 Session *s;
2260 u_int i;
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;
2278 if (s->display) {
2279 xfree(s->display);
2280 s->display = NULL;
2282 if (s->auth_proto) {
2283 xfree(s->auth_proto);
2284 s->auth_proto = NULL;
2286 if (s->auth_data) {
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;
2296 static void
2297 session_exit_message(Session *s, int status)
2299 Channel *c;
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));
2310 packet_send();
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("");
2317 packet_send();
2318 } else {
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);
2343 void
2344 session_close(Session *s)
2346 u_int i;
2348 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2349 if (s->ttyfd != -1)
2350 session_pty_cleanup(s);
2351 if (s->term)
2352 xfree(s->term);
2353 if (s->display)
2354 xfree(s->display);
2355 if (s->x11_chanids)
2356 xfree(s->x11_chanids);
2357 if (s->auth_display)
2358 xfree(s->auth_display);
2359 if (s->auth_data)
2360 xfree(s->auth_data);
2361 if (s->auth_proto)
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);
2368 xfree(s->env);
2370 session_proctitle(s);
2371 session_unused(s->self);
2374 void
2375 session_close_by_pid(pid_t pid, int status)
2377 Session *s = session_by_pid(pid);
2378 if (s == NULL) {
2379 debug("session_close_by_pid: no session for pid %ld",
2380 (long)pid);
2381 return;
2383 if (s->chanid != -1)
2384 session_exit_message(s, status);
2385 if (s->ttyfd != -1)
2386 session_pty_cleanup(s);
2387 s->pid = 0;
2391 * this is called when a channel dies before
2392 * the session 'child' itself dies
2394 void
2395 session_close_by_channel(int id, void *arg)
2397 Session *s = session_by_channel(id);
2398 u_int i;
2400 if (s == NULL) {
2401 debug("session_close_by_channel: no session for id %d", id);
2402 return;
2404 debug("session_close_by_channel: channel %d child %ld",
2405 id, (long)s->pid);
2406 if (s->pid != 0) {
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
2412 if (s->ttyfd != -1)
2413 session_pty_cleanup(s);
2414 return;
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;
2427 s->chanid = -1;
2428 session_close(s);
2431 void
2432 session_destroy_all(void (*closefunc)(Session *))
2434 int i;
2435 for (i = 0; i < sessions_nalloc; i++) {
2436 Session *s = &sessions[i];
2437 if (s->used) {
2438 if (closefunc != NULL)
2439 closefunc(s);
2440 else
2441 session_close(s);
2446 static char *
2447 session_tty_list(void)
2449 static char buf[1024];
2450 int i;
2451 buf[0] = '\0';
2452 for (i = 0; i < sessions_nalloc; i++) {
2453 Session *s = &sessions[i];
2454 if (s->used && s->ttyfd != -1) {
2455 char *p;
2456 if (buf[0] != '\0')
2457 strlcat(buf, ",", sizeof buf);
2458 if ((p = strstr(s->tty, "/pts/")) != NULL)
2459 p++;
2460 else {
2461 if ((p = strrchr(s->tty, '/')) != NULL)
2462 p++;
2463 else
2464 p = s->tty;
2466 strlcat(buf, p, sizeof buf);
2469 if (buf[0] == '\0')
2470 strlcpy(buf, "notty", sizeof buf);
2471 return buf;
2474 void
2475 session_proctitle(Session *s)
2477 if (s->pw == NULL)
2478 error("no user for session %d", s->self);
2479 else
2480 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2484 session_setup_x11fwd(Session *s)
2486 struct stat st;
2487 char display[512], auth_display[512];
2488 char hostname[MAXHOSTNAMELEN];
2489 u_int i;
2491 if (no_x11_forwarding_flag) {
2492 packet_send_debug("X11 forwarding disabled in user configuration file.");
2493 return 0;
2495 if (!options.x11_forwarding) {
2496 debug("X11 forwarding disabled in server configuration file.");
2497 return 0;
2499 if (!options.xauth_location ||
2500 (stat(options.xauth_location, &st) == -1)) {
2501 packet_send_debug("No xauth program; cannot forward with spoofing.");
2502 return 0;
2504 if (options.use_login) {
2505 packet_send_debug("X11 forwarding disabled; "
2506 "not compatible with UseLogin=yes.");
2507 return 0;
2509 if (s->display != NULL) {
2510 debug("X11 display already set.");
2511 return 0;
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.");
2517 return 0;
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);
2539 } else {
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);
2546 return 1;
2549 static void
2550 do_authenticated2(Authctxt *authctxt)
2552 server_loop2(authctxt);
2555 void
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 */
2563 if (is_child)
2564 return;
2566 /* avoid double cleanup */
2567 if (called)
2568 return;
2569 called = 1;
2571 if (authctxt == NULL || !authctxt->authenticated)
2572 return;
2573 #ifdef KRB4
2574 if (options.kerberos_ticket_cleanup)
2575 krb4_cleanup_proc(authctxt);
2576 #endif
2577 #ifdef KRB5
2578 if (options.kerberos_ticket_cleanup &&
2579 authctxt->krb5_ctx)
2580 krb5_cleanup_proc(authctxt);
2581 #endif
2583 #ifdef GSSAPI
2584 if (compat20 && options.gss_cleanup_creds)
2585 ssh_gssapi_cleanup_creds();
2586 #endif
2588 #ifdef USE_PAM
2589 if (options.use_pam) {
2590 sshpam_cleanup();
2591 sshpam_thread_cleanup();
2593 #endif
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);