HAMMER 60I/Many: Mirroring
[dragonfly.git] / crypto / openssh-5 / session.c
blobe50d6f453c7c55880e22e315dab16e6776495f04
1 /* $OpenBSD: session.c,v 1.233 2008/03/26 21:28:14 djm Exp $ */
2 /*
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4 * All rights reserved
6 * As far as I am concerned, the code I have written for this software
7 * can be used freely for any purpose. Any derived versions of this
8 * software must be clearly marked as such, and if the derived work is
9 * incompatible with the protocol description in the RFC file, it must be
10 * called by a name other than "ssh" or "Secure Shell".
12 * SSH2 support by Markus Friedl.
13 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
17 * are met:
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
24 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 #include "includes.h"
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #ifdef HAVE_SYS_STAT_H
41 # include <sys/stat.h>
42 #endif
43 #include <sys/socket.h>
44 #include <sys/un.h>
45 #include <sys/wait.h>
47 #include <arpa/inet.h>
49 #include <errno.h>
50 #include <grp.h>
51 #ifdef HAVE_PATHS_H
52 #include <paths.h>
53 #endif
54 #include <pwd.h>
55 #include <signal.h>
56 #include <stdarg.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <unistd.h>
62 #include "xmalloc.h"
63 #include "ssh.h"
64 #include "ssh1.h"
65 #include "ssh2.h"
66 #include "sshpty.h"
67 #include "packet.h"
68 #include "buffer.h"
69 #include "match.h"
70 #include "uidswap.h"
71 #include "compat.h"
72 #include "channels.h"
73 #include "key.h"
74 #include "cipher.h"
75 #ifdef GSSAPI
76 #include "ssh-gss.h"
77 #endif
78 #include "hostfile.h"
79 #include "auth.h"
80 #include "auth-options.h"
81 #include "pathnames.h"
82 #include "log.h"
83 #include "servconf.h"
84 #include "sshlogin.h"
85 #include "serverloop.h"
86 #include "canohost.h"
87 #include "misc.h"
88 #include "session.h"
89 #include "kex.h"
90 #include "monitor_wrap.h"
91 #include "sftp.h"
93 #if defined(KRB5) && defined(USE_AFS)
94 #include <kafs.h>
95 #endif
97 /* func */
99 Session *session_new(void);
100 void session_set_fds(Session *, int, int, int);
101 void session_pty_cleanup(Session *);
102 void session_proctitle(Session *);
103 int session_setup_x11fwd(Session *);
104 void do_exec_pty(Session *, const char *);
105 void do_exec_no_pty(Session *, const char *);
106 void do_exec(Session *, const char *);
107 void do_login(Session *, const char *);
108 #ifdef LOGIN_NEEDS_UTMPX
109 static void do_pre_login(Session *s);
110 #endif
111 void do_child(Session *, const char *);
112 void do_motd(void);
113 int check_quietlogin(Session *, const char *);
115 static void do_authenticated1(Authctxt *);
116 static void do_authenticated2(Authctxt *);
118 static int session_pty_req(Session *);
120 /* import */
121 extern ServerOptions options;
122 extern char *__progname;
123 extern int log_stderr;
124 extern int debug_flag;
125 extern u_int utmp_len;
126 extern int startup_pipe;
127 extern void destroy_sensitive_data(void);
128 extern Buffer loginmsg;
130 /* original command from peer. */
131 const char *original_command = NULL;
133 /* data */
134 #define MAX_SESSIONS 20
135 Session sessions[MAX_SESSIONS];
137 #define SUBSYSTEM_NONE 0
138 #define SUBSYSTEM_EXT 1
139 #define SUBSYSTEM_INT_SFTP 2
141 #ifdef HAVE_LOGIN_CAP
142 login_cap_t *lc;
143 #endif
145 static int is_child = 0;
147 /* Name and directory of socket for authentication agent forwarding. */
148 static char *auth_sock_name = NULL;
149 static char *auth_sock_dir = NULL;
151 /* removes the agent forwarding socket */
153 static void
154 auth_sock_cleanup_proc(struct passwd *pw)
156 if (auth_sock_name != NULL) {
157 temporarily_use_uid(pw);
158 unlink(auth_sock_name);
159 rmdir(auth_sock_dir);
160 auth_sock_name = NULL;
161 restore_uid();
165 static int
166 auth_input_request_forwarding(struct passwd * pw)
168 Channel *nc;
169 int sock;
170 struct sockaddr_un sunaddr;
172 if (auth_sock_name != NULL) {
173 error("authentication forwarding requested twice.");
174 return 0;
177 /* Temporarily drop privileged uid for mkdir/bind. */
178 temporarily_use_uid(pw);
180 /* Allocate a buffer for the socket name, and format the name. */
181 auth_sock_name = xmalloc(MAXPATHLEN);
182 auth_sock_dir = xmalloc(MAXPATHLEN);
183 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
185 /* Create private directory for socket */
186 if (mkdtemp(auth_sock_dir) == NULL) {
187 packet_send_debug("Agent forwarding disabled: "
188 "mkdtemp() failed: %.100s", strerror(errno));
189 restore_uid();
190 xfree(auth_sock_name);
191 xfree(auth_sock_dir);
192 auth_sock_name = NULL;
193 auth_sock_dir = NULL;
194 return 0;
196 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
197 auth_sock_dir, (long) getpid());
199 /* Create the socket. */
200 sock = socket(AF_UNIX, SOCK_STREAM, 0);
201 if (sock < 0)
202 packet_disconnect("socket: %.100s", strerror(errno));
204 /* Bind it to the name. */
205 memset(&sunaddr, 0, sizeof(sunaddr));
206 sunaddr.sun_family = AF_UNIX;
207 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
209 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0)
210 packet_disconnect("bind: %.100s", strerror(errno));
212 /* Restore the privileged uid. */
213 restore_uid();
215 /* Start listening on the socket. */
216 if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
217 packet_disconnect("listen: %.100s", strerror(errno));
219 /* Allocate a channel for the authentication agent socket. */
220 nc = channel_new("auth socket",
221 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
222 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
223 0, "auth socket", 1);
224 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
225 return 1;
228 static void
229 display_loginmsg(void)
231 if (buffer_len(&loginmsg) > 0) {
232 buffer_append(&loginmsg, "\0", 1);
233 printf("%s", (char *)buffer_ptr(&loginmsg));
234 buffer_clear(&loginmsg);
238 void
239 do_authenticated(Authctxt *authctxt)
241 setproctitle("%s", authctxt->pw->pw_name);
243 /* setup the channel layer */
244 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
245 channel_permit_all_opens();
247 if (compat20)
248 do_authenticated2(authctxt);
249 else
250 do_authenticated1(authctxt);
252 do_cleanup(authctxt);
256 * Prepares for an interactive session. This is called after the user has
257 * been successfully authenticated. During this message exchange, pseudo
258 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
259 * are requested, etc.
261 static void
262 do_authenticated1(Authctxt *authctxt)
264 Session *s;
265 char *command;
266 int success, type, screen_flag;
267 int enable_compression_after_reply = 0;
268 u_int proto_len, data_len, dlen, compression_level = 0;
270 s = session_new();
271 if (s == NULL) {
272 error("no more sessions");
273 return;
275 s->authctxt = authctxt;
276 s->pw = authctxt->pw;
279 * We stay in this loop until the client requests to execute a shell
280 * or a command.
282 for (;;) {
283 success = 0;
285 /* Get a packet from the client. */
286 type = packet_read();
288 /* Process the packet. */
289 switch (type) {
290 case SSH_CMSG_REQUEST_COMPRESSION:
291 compression_level = packet_get_int();
292 packet_check_eom();
293 if (compression_level < 1 || compression_level > 9) {
294 packet_send_debug("Received invalid compression level %d.",
295 compression_level);
296 break;
298 if (options.compression == COMP_NONE) {
299 debug2("compression disabled");
300 break;
302 /* Enable compression after we have responded with SUCCESS. */
303 enable_compression_after_reply = 1;
304 success = 1;
305 break;
307 case SSH_CMSG_REQUEST_PTY:
308 success = session_pty_req(s);
309 break;
311 case SSH_CMSG_X11_REQUEST_FORWARDING:
312 s->auth_proto = packet_get_string(&proto_len);
313 s->auth_data = packet_get_string(&data_len);
315 screen_flag = packet_get_protocol_flags() &
316 SSH_PROTOFLAG_SCREEN_NUMBER;
317 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
319 if (packet_remaining() == 4) {
320 if (!screen_flag)
321 debug2("Buggy client: "
322 "X11 screen flag missing");
323 s->screen = packet_get_int();
324 } else {
325 s->screen = 0;
327 packet_check_eom();
328 success = session_setup_x11fwd(s);
329 if (!success) {
330 xfree(s->auth_proto);
331 xfree(s->auth_data);
332 s->auth_proto = NULL;
333 s->auth_data = NULL;
335 break;
337 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
338 if (no_agent_forwarding_flag || compat13) {
339 debug("Authentication agent forwarding not permitted for this authentication.");
340 break;
342 debug("Received authentication agent forwarding request.");
343 success = auth_input_request_forwarding(s->pw);
344 break;
346 case SSH_CMSG_PORT_FORWARD_REQUEST:
347 if (no_port_forwarding_flag) {
348 debug("Port forwarding not permitted for this authentication.");
349 break;
351 if (!options.allow_tcp_forwarding) {
352 debug("Port forwarding not permitted.");
353 break;
355 debug("Received TCP/IP port forwarding request.");
356 if (channel_input_port_forward_request(s->pw->pw_uid == 0,
357 options.gateway_ports) < 0) {
358 debug("Port forwarding failed.");
359 break;
361 success = 1;
362 break;
364 case SSH_CMSG_MAX_PACKET_SIZE:
365 if (packet_set_maxsize(packet_get_int()) > 0)
366 success = 1;
367 break;
369 case SSH_CMSG_EXEC_SHELL:
370 case SSH_CMSG_EXEC_CMD:
371 if (type == SSH_CMSG_EXEC_CMD) {
372 command = packet_get_string(&dlen);
373 debug("Exec command '%.500s'", command);
374 do_exec(s, command);
375 xfree(command);
376 } else {
377 do_exec(s, NULL);
379 packet_check_eom();
380 session_close(s);
381 return;
383 default:
385 * Any unknown messages in this phase are ignored,
386 * and a failure message is returned.
388 logit("Unknown packet type received after authentication: %d", type);
390 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
391 packet_send();
392 packet_write_wait();
394 /* Enable compression now that we have replied if appropriate. */
395 if (enable_compression_after_reply) {
396 enable_compression_after_reply = 0;
397 packet_start_compression(compression_level);
403 * This is called to fork and execute a command when we have no tty. This
404 * will call do_child from the child, and server_loop from the parent after
405 * setting up file descriptors and such.
407 void
408 do_exec_no_pty(Session *s, const char *command)
410 pid_t pid;
412 #ifdef USE_PIPES
413 int pin[2], pout[2], perr[2];
414 /* Allocate pipes for communicating with the program. */
415 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
416 packet_disconnect("Could not create pipes: %.100s",
417 strerror(errno));
418 #else /* USE_PIPES */
419 int inout[2], err[2];
420 /* Uses socket pairs to communicate with the program. */
421 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
422 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
423 packet_disconnect("Could not create socket pairs: %.100s",
424 strerror(errno));
425 #endif /* USE_PIPES */
426 if (s == NULL)
427 fatal("do_exec_no_pty: no session");
429 session_proctitle(s);
431 /* Fork the child. */
432 if ((pid = fork()) == 0) {
433 is_child = 1;
435 /* Child. Reinitialize the log since the pid has changed. */
436 log_init(__progname, options.log_level, options.log_facility, log_stderr);
439 * Create a new session and process group since the 4.4BSD
440 * setlogin() affects the entire process group.
442 if (setsid() < 0)
443 error("setsid failed: %.100s", strerror(errno));
445 #ifdef USE_PIPES
447 * Redirect stdin. We close the parent side of the socket
448 * pair, and make the child side the standard input.
450 close(pin[1]);
451 if (dup2(pin[0], 0) < 0)
452 perror("dup2 stdin");
453 close(pin[0]);
455 /* Redirect stdout. */
456 close(pout[0]);
457 if (dup2(pout[1], 1) < 0)
458 perror("dup2 stdout");
459 close(pout[1]);
461 /* Redirect stderr. */
462 close(perr[0]);
463 if (dup2(perr[1], 2) < 0)
464 perror("dup2 stderr");
465 close(perr[1]);
466 #else /* USE_PIPES */
468 * Redirect stdin, stdout, and stderr. Stdin and stdout will
469 * use the same socket, as some programs (particularly rdist)
470 * seem to depend on it.
472 close(inout[1]);
473 close(err[1]);
474 if (dup2(inout[0], 0) < 0) /* stdin */
475 perror("dup2 stdin");
476 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
477 perror("dup2 stdout");
478 if (dup2(err[0], 2) < 0) /* stderr */
479 perror("dup2 stderr");
480 #endif /* USE_PIPES */
482 #ifdef _UNICOS
483 cray_init_job(s->pw); /* set up cray jid and tmpdir */
484 #endif
486 /* Do processing for the child (exec command etc). */
487 do_child(s, command);
488 /* NOTREACHED */
490 #ifdef _UNICOS
491 signal(WJSIGNAL, cray_job_termination_handler);
492 #endif /* _UNICOS */
493 #ifdef HAVE_CYGWIN
494 if (is_winnt)
495 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
496 #endif
497 if (pid < 0)
498 packet_disconnect("fork failed: %.100s", strerror(errno));
499 s->pid = pid;
500 /* Set interactive/non-interactive mode. */
501 packet_set_interactive(s->display != NULL);
502 #ifdef USE_PIPES
503 /* We are the parent. Close the child sides of the pipes. */
504 close(pin[0]);
505 close(pout[1]);
506 close(perr[1]);
508 if (compat20) {
509 if (s->is_subsystem) {
510 close(perr[0]);
511 perr[0] = -1;
513 session_set_fds(s, pin[1], pout[0], perr[0]);
514 } else {
515 /* Enter the interactive session. */
516 server_loop(pid, pin[1], pout[0], perr[0]);
517 /* server_loop has closed pin[1], pout[0], and perr[0]. */
519 #else /* USE_PIPES */
520 /* We are the parent. Close the child sides of the socket pairs. */
521 close(inout[0]);
522 close(err[0]);
525 * Clear loginmsg, since it's the child's responsibility to display
526 * it to the user, otherwise multiple sessions may accumulate
527 * multiple copies of the login messages.
529 buffer_clear(&loginmsg);
532 * Enter the interactive session. Note: server_loop must be able to
533 * handle the case that fdin and fdout are the same.
535 if (compat20) {
536 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
537 } else {
538 server_loop(pid, inout[1], inout[1], err[1]);
539 /* server_loop has closed inout[1] and err[1]. */
541 #endif /* USE_PIPES */
545 * This is called to fork and execute a command when we have a tty. This
546 * will call do_child from the child, and server_loop from the parent after
547 * setting up file descriptors, controlling tty, updating wtmp, utmp,
548 * lastlog, and other such operations.
550 void
551 do_exec_pty(Session *s, const char *command)
553 int fdout, ptyfd, ttyfd, ptymaster;
554 pid_t pid;
556 if (s == NULL)
557 fatal("do_exec_pty: no session");
558 ptyfd = s->ptyfd;
559 ttyfd = s->ttyfd;
561 /* Fork the child. */
562 if ((pid = fork()) == 0) {
563 is_child = 1;
565 /* Child. Reinitialize the log because the pid has changed. */
566 log_init(__progname, options.log_level, options.log_facility, log_stderr);
567 /* Close the master side of the pseudo tty. */
568 close(ptyfd);
570 /* Make the pseudo tty our controlling tty. */
571 pty_make_controlling_tty(&ttyfd, s->tty);
573 /* Redirect stdin/stdout/stderr from the pseudo tty. */
574 if (dup2(ttyfd, 0) < 0)
575 error("dup2 stdin: %s", strerror(errno));
576 if (dup2(ttyfd, 1) < 0)
577 error("dup2 stdout: %s", strerror(errno));
578 if (dup2(ttyfd, 2) < 0)
579 error("dup2 stderr: %s", strerror(errno));
581 /* Close the extra descriptor for the pseudo tty. */
582 close(ttyfd);
584 /* record login, etc. similar to login(1) */
585 #ifndef HAVE_OSF_SIA
586 if (!(options.use_login && command == NULL)) {
587 #ifdef _UNICOS
588 cray_init_job(s->pw); /* set up cray jid and tmpdir */
589 #endif /* _UNICOS */
590 do_login(s, command);
592 # ifdef LOGIN_NEEDS_UTMPX
593 else
594 do_pre_login(s);
595 # endif
596 #endif
598 /* Do common processing for the child, such as execing the command. */
599 do_child(s, command);
600 /* NOTREACHED */
602 #ifdef _UNICOS
603 signal(WJSIGNAL, cray_job_termination_handler);
604 #endif /* _UNICOS */
605 #ifdef HAVE_CYGWIN
606 if (is_winnt)
607 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
608 #endif
609 if (pid < 0)
610 packet_disconnect("fork failed: %.100s", strerror(errno));
611 s->pid = pid;
613 /* Parent. Close the slave side of the pseudo tty. */
614 close(ttyfd);
617 * Create another descriptor of the pty master side for use as the
618 * standard input. We could use the original descriptor, but this
619 * simplifies code in server_loop. The descriptor is bidirectional.
621 fdout = dup(ptyfd);
622 if (fdout < 0)
623 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
625 /* we keep a reference to the pty master */
626 ptymaster = dup(ptyfd);
627 if (ptymaster < 0)
628 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
629 s->ptymaster = ptymaster;
631 /* Enter interactive session. */
632 packet_set_interactive(1);
633 if (compat20) {
634 session_set_fds(s, ptyfd, fdout, -1);
635 } else {
636 server_loop(pid, ptyfd, fdout, -1);
637 /* server_loop _has_ closed ptyfd and fdout. */
641 #ifdef LOGIN_NEEDS_UTMPX
642 static void
643 do_pre_login(Session *s)
645 socklen_t fromlen;
646 struct sockaddr_storage from;
647 pid_t pid = getpid();
650 * Get IP address of client. If the connection is not a socket, let
651 * the address be 0.0.0.0.
653 memset(&from, 0, sizeof(from));
654 fromlen = sizeof(from);
655 if (packet_connection_is_on_socket()) {
656 if (getpeername(packet_get_connection_in(),
657 (struct sockaddr *)&from, &fromlen) < 0) {
658 debug("getpeername: %.100s", strerror(errno));
659 cleanup_exit(255);
663 record_utmp_only(pid, s->tty, s->pw->pw_name,
664 get_remote_name_or_ip(utmp_len, options.use_dns),
665 (struct sockaddr *)&from, fromlen);
667 #endif
670 * This is called to fork and execute a command. If another command is
671 * to be forced, execute that instead.
673 void
674 do_exec(Session *s, const char *command)
676 if (options.adm_forced_command) {
677 original_command = command;
678 command = options.adm_forced_command;
679 if (strcmp(INTERNAL_SFTP_NAME, command) == 0)
680 s->is_subsystem = SUBSYSTEM_INT_SFTP;
681 else if (s->is_subsystem)
682 s->is_subsystem = SUBSYSTEM_EXT;
683 debug("Forced command (config) '%.900s'", command);
684 } else if (forced_command) {
685 original_command = command;
686 command = forced_command;
687 if (strcmp(INTERNAL_SFTP_NAME, command) == 0)
688 s->is_subsystem = SUBSYSTEM_INT_SFTP;
689 else if (s->is_subsystem)
690 s->is_subsystem = SUBSYSTEM_EXT;
691 debug("Forced command (key option) '%.900s'", command);
694 #ifdef SSH_AUDIT_EVENTS
695 if (command != NULL)
696 PRIVSEP(audit_run_command(command));
697 else if (s->ttyfd == -1) {
698 char *shell = s->pw->pw_shell;
700 if (shell[0] == '\0') /* empty shell means /bin/sh */
701 shell =_PATH_BSHELL;
702 PRIVSEP(audit_run_command(shell));
704 #endif
705 if (s->ttyfd != -1)
706 do_exec_pty(s, command);
707 else
708 do_exec_no_pty(s, command);
710 original_command = NULL;
713 * Clear loginmsg: it's the child's responsibility to display
714 * it to the user, otherwise multiple sessions may accumulate
715 * multiple copies of the login messages.
717 buffer_clear(&loginmsg);
720 /* administrative, login(1)-like work */
721 void
722 do_login(Session *s, const char *command)
724 socklen_t fromlen;
725 struct sockaddr_storage from;
726 struct passwd * pw = s->pw;
727 pid_t pid = getpid();
730 * Get IP address of client. If the connection is not a socket, let
731 * the address be 0.0.0.0.
733 memset(&from, 0, sizeof(from));
734 fromlen = sizeof(from);
735 if (packet_connection_is_on_socket()) {
736 if (getpeername(packet_get_connection_in(),
737 (struct sockaddr *) & from, &fromlen) < 0) {
738 debug("getpeername: %.100s", strerror(errno));
739 cleanup_exit(255);
743 /* Record that there was a login on that tty from the remote host. */
744 if (!use_privsep)
745 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
746 get_remote_name_or_ip(utmp_len,
747 options.use_dns),
748 (struct sockaddr *)&from, fromlen);
750 #ifdef USE_PAM
752 * If password change is needed, do it now.
753 * This needs to occur before the ~/.hushlogin check.
755 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
756 display_loginmsg();
757 do_pam_chauthtok();
758 s->authctxt->force_pwchange = 0;
759 /* XXX - signal [net] parent to enable forwardings */
761 #endif
763 if (check_quietlogin(s, command))
764 return;
766 display_loginmsg();
768 do_motd();
772 * Display the message of the day.
774 void
775 do_motd(void)
777 FILE *f;
778 char buf[256];
779 #ifdef HAVE_LOGIN_CAP
780 const char *fname;
781 #endif
783 #ifdef HAVE_LOGIN_CAP
784 fname = login_getcapstr(lc, "copyright", NULL, NULL);
785 if (fname != NULL && (f = fopen(fname, "r")) != NULL) {
786 while (fgets(buf, sizeof(buf), f) != NULL)
787 fputs(buf, stdout);
788 fclose(f);
789 } else
790 #endif /* HAVE_LOGIN_CAP */
791 (void)printf("%s\n\t%s %s\n",
792 "Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
793 "The Regents of the University of California. ",
794 "All rights reserved.");
796 (void)printf("\n");
798 if (options.print_motd) {
799 #ifdef HAVE_LOGIN_CAP
800 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
801 "/etc/motd"), "r");
802 #else
803 f = fopen("/etc/motd", "r");
804 #endif
805 if (f) {
806 while (fgets(buf, sizeof(buf), f))
807 fputs(buf, stdout);
808 fclose(f);
815 * Check for quiet login, either .hushlogin or command given.
818 check_quietlogin(Session *s, const char *command)
820 char buf[256];
821 struct passwd *pw = s->pw;
822 struct stat st;
824 /* Return 1 if .hushlogin exists or a command given. */
825 if (command != NULL)
826 return 1;
827 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
828 #ifdef HAVE_LOGIN_CAP
829 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
830 return 1;
831 #else
832 if (stat(buf, &st) >= 0)
833 return 1;
834 #endif
835 return 0;
839 * Sets the value of the given variable in the environment. If the variable
840 * already exists, its value is overriden.
842 void
843 child_set_env(char ***envp, u_int *envsizep, const char *name,
844 const char *value)
846 char **env;
847 u_int envsize;
848 u_int i, namelen;
851 * If we're passed an uninitialized list, allocate a single null
852 * entry before continuing.
854 if (*envp == NULL && *envsizep == 0) {
855 *envp = xmalloc(sizeof(char *));
856 *envp[0] = NULL;
857 *envsizep = 1;
861 * Find the slot where the value should be stored. If the variable
862 * already exists, we reuse the slot; otherwise we append a new slot
863 * at the end of the array, expanding if necessary.
865 env = *envp;
866 namelen = strlen(name);
867 for (i = 0; env[i]; i++)
868 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
869 break;
870 if (env[i]) {
871 /* Reuse the slot. */
872 xfree(env[i]);
873 } else {
874 /* New variable. Expand if necessary. */
875 envsize = *envsizep;
876 if (i >= envsize - 1) {
877 if (envsize >= 1000)
878 fatal("child_set_env: too many env vars");
879 envsize += 50;
880 env = (*envp) = xrealloc(env, envsize, sizeof(char *));
881 *envsizep = envsize;
883 /* Need to set the NULL pointer at end of array beyond the new slot. */
884 env[i + 1] = NULL;
887 /* Allocate space and format the variable in the appropriate slot. */
888 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
889 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
893 * Reads environment variables from the given file and adds/overrides them
894 * into the environment. If the file does not exist, this does nothing.
895 * Otherwise, it must consist of empty lines, comments (line starts with '#')
896 * and assignments of the form name=value. No other forms are allowed.
898 static void
899 read_environment_file(char ***env, u_int *envsize,
900 const char *filename)
902 FILE *f;
903 char buf[4096];
904 char *cp, *value;
905 u_int lineno = 0;
907 f = fopen(filename, "r");
908 if (!f)
909 return;
911 while (fgets(buf, sizeof(buf), f)) {
912 if (++lineno > 1000)
913 fatal("Too many lines in environment file %s", filename);
914 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
916 if (!*cp || *cp == '#' || *cp == '\n')
917 continue;
919 cp[strcspn(cp, "\n")] = '\0';
921 value = strchr(cp, '=');
922 if (value == NULL) {
923 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
924 filename);
925 continue;
928 * Replace the equals sign by nul, and advance value to
929 * the value string.
931 *value = '\0';
932 value++;
933 child_set_env(env, envsize, cp, value);
935 fclose(f);
938 #ifdef HAVE_ETC_DEFAULT_LOGIN
940 * Return named variable from specified environment, or NULL if not present.
942 static char *
943 child_get_env(char **env, const char *name)
945 int i;
946 size_t len;
948 len = strlen(name);
949 for (i=0; env[i] != NULL; i++)
950 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
951 return(env[i] + len + 1);
952 return NULL;
956 * Read /etc/default/login.
957 * We pick up the PATH (or SUPATH for root) and UMASK.
959 static void
960 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
962 char **tmpenv = NULL, *var;
963 u_int i, tmpenvsize = 0;
964 u_long mask;
967 * We don't want to copy the whole file to the child's environment,
968 * so we use a temporary environment and copy the variables we're
969 * interested in.
971 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
973 if (tmpenv == NULL)
974 return;
976 if (uid == 0)
977 var = child_get_env(tmpenv, "SUPATH");
978 else
979 var = child_get_env(tmpenv, "PATH");
980 if (var != NULL)
981 child_set_env(env, envsize, "PATH", var);
983 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
984 if (sscanf(var, "%5lo", &mask) == 1)
985 umask((mode_t)mask);
987 for (i = 0; tmpenv[i] != NULL; i++)
988 xfree(tmpenv[i]);
989 xfree(tmpenv);
991 #endif /* HAVE_ETC_DEFAULT_LOGIN */
993 void
994 copy_environment(char **source, char ***env, u_int *envsize)
996 char *var_name, *var_val;
997 int i;
999 if (source == NULL)
1000 return;
1002 for(i = 0; source[i] != NULL; i++) {
1003 var_name = xstrdup(source[i]);
1004 if ((var_val = strstr(var_name, "=")) == NULL) {
1005 xfree(var_name);
1006 continue;
1008 *var_val++ = '\0';
1010 debug3("Copy environment: %s=%s", var_name, var_val);
1011 child_set_env(env, envsize, var_name, var_val);
1013 xfree(var_name);
1017 static char **
1018 do_setup_env(Session *s, const char *shell)
1020 char buf[256];
1021 u_int i, envsize;
1022 char **env, *laddr;
1023 struct passwd *pw = s->pw;
1024 #ifndef HAVE_LOGIN_CAP
1025 char *path = NULL;
1026 #else
1027 extern char **environ;
1028 char **senv, **var;
1029 #endif
1031 /* Initialize the environment. */
1032 envsize = 100;
1033 env = xcalloc(envsize, sizeof(char *));
1034 env[0] = NULL;
1036 #ifdef HAVE_CYGWIN
1038 * The Windows environment contains some setting which are
1039 * important for a running system. They must not be dropped.
1042 char **p;
1044 p = fetch_windows_environment();
1045 copy_environment(p, &env, &envsize);
1046 free_windows_environment(p);
1048 #endif
1050 if (getenv("TZ"))
1051 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1053 #ifdef GSSAPI
1054 /* Allow any GSSAPI methods that we've used to alter
1055 * the childs environment as they see fit
1057 ssh_gssapi_do_child(&env, &envsize);
1058 #endif
1060 if (!options.use_login) {
1061 /* Set basic environment. */
1062 for (i = 0; i < s->num_env; i++)
1063 child_set_env(&env, &envsize, s->env[i].name,
1064 s->env[i].val);
1066 child_set_env(&env, &envsize, "USER", pw->pw_name);
1067 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1068 #ifdef _AIX
1069 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1070 #endif
1071 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1072 snprintf(buf, sizeof buf, "%.200s/%.50s",
1073 _PATH_MAILDIR, pw->pw_name);
1074 child_set_env(&env, &envsize, "MAIL", buf);
1075 #ifdef HAVE_LOGIN_CAP
1076 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1077 child_set_env(&env, &envsize, "TERM", "su");
1078 senv = environ;
1079 environ = xmalloc(sizeof(char *));
1080 *environ = NULL;
1081 (void) setusercontext(lc, pw, pw->pw_uid,
1082 LOGIN_SETENV|LOGIN_SETPATH);
1083 copy_environment(environ, &env, &envsize);
1084 for (var = environ; *var != NULL; ++var)
1085 xfree(*var);
1086 xfree(environ);
1087 environ = senv;
1088 #else /* HAVE_LOGIN_CAP */
1089 # ifndef HAVE_CYGWIN
1091 * There's no standard path on Windows. The path contains
1092 * important components pointing to the system directories,
1093 * needed for loading shared libraries. So the path better
1094 * remains intact here.
1096 # ifdef HAVE_ETC_DEFAULT_LOGIN
1097 read_etc_default_login(&env, &envsize, pw->pw_uid);
1098 path = child_get_env(env, "PATH");
1099 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1100 if (path == NULL || *path == '\0') {
1101 child_set_env(&env, &envsize, "PATH",
1102 s->pw->pw_uid == 0 ?
1103 SUPERUSER_PATH : _PATH_STDPATH);
1105 # endif /* HAVE_CYGWIN */
1106 #endif /* HAVE_LOGIN_CAP */
1108 /* Normal systems set SHELL by default. */
1109 child_set_env(&env, &envsize, "SHELL", shell);
1112 /* Set custom environment options from RSA authentication. */
1113 if (!options.use_login) {
1114 while (custom_environment) {
1115 struct envstring *ce = custom_environment;
1116 char *str = ce->s;
1118 for (i = 0; str[i] != '=' && str[i]; i++)
1120 if (str[i] == '=') {
1121 str[i] = 0;
1122 child_set_env(&env, &envsize, str, str + i + 1);
1124 custom_environment = ce->next;
1125 xfree(ce->s);
1126 xfree(ce);
1130 /* SSH_CLIENT deprecated */
1131 snprintf(buf, sizeof buf, "%.50s %d %d",
1132 get_remote_ipaddr(), get_remote_port(), get_local_port());
1133 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1135 laddr = get_local_ipaddr(packet_get_connection_in());
1136 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1137 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1138 xfree(laddr);
1139 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1141 if (s->ttyfd != -1)
1142 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1143 if (s->term)
1144 child_set_env(&env, &envsize, "TERM", s->term);
1145 if (s->display)
1146 child_set_env(&env, &envsize, "DISPLAY", s->display);
1147 if (original_command)
1148 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1149 original_command);
1151 #ifdef _UNICOS
1152 if (cray_tmpdir[0] != '\0')
1153 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1154 #endif /* _UNICOS */
1157 * Since we clear KRB5CCNAME at startup, if it's set now then it
1158 * must have been set by a native authentication method (eg AIX or
1159 * SIA), so copy it to the child.
1162 char *cp;
1164 if ((cp = getenv("KRB5CCNAME")) != NULL)
1165 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1168 #ifdef _AIX
1170 char *cp;
1172 if ((cp = getenv("AUTHSTATE")) != NULL)
1173 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1174 read_environment_file(&env, &envsize, "/etc/environment");
1176 #endif
1177 #ifdef KRB5
1178 if (s->authctxt->krb5_ccname)
1179 child_set_env(&env, &envsize, "KRB5CCNAME",
1180 s->authctxt->krb5_ccname);
1181 #endif
1182 #ifdef USE_PAM
1184 * Pull in any environment variables that may have
1185 * been set by PAM.
1187 if (options.use_pam) {
1188 char **p;
1190 p = fetch_pam_child_environment();
1191 copy_environment(p, &env, &envsize);
1192 free_pam_environment(p);
1194 p = fetch_pam_environment();
1195 copy_environment(p, &env, &envsize);
1196 free_pam_environment(p);
1198 #endif /* USE_PAM */
1200 if (auth_sock_name != NULL)
1201 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1202 auth_sock_name);
1204 /* read $HOME/.ssh/environment. */
1205 if (options.permit_user_env && !options.use_login) {
1206 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1207 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1208 read_environment_file(&env, &envsize, buf);
1210 if (debug_flag) {
1211 /* dump the environment */
1212 fprintf(stderr, "Environment:\n");
1213 for (i = 0; env[i]; i++)
1214 fprintf(stderr, " %.200s\n", env[i]);
1216 return env;
1220 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1221 * first in this order).
1223 static void
1224 do_rc_files(Session *s, const char *shell)
1226 FILE *f = NULL;
1227 char cmd[1024];
1228 int do_xauth;
1229 struct stat st;
1231 do_xauth =
1232 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1234 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1235 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1236 !no_user_rc && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1237 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1238 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1239 if (debug_flag)
1240 fprintf(stderr, "Running %s\n", cmd);
1241 f = popen(cmd, "w");
1242 if (f) {
1243 if (do_xauth)
1244 fprintf(f, "%s %s\n", s->auth_proto,
1245 s->auth_data);
1246 pclose(f);
1247 } else
1248 fprintf(stderr, "Could not run %s\n",
1249 _PATH_SSH_USER_RC);
1250 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1251 if (debug_flag)
1252 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1253 _PATH_SSH_SYSTEM_RC);
1254 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1255 if (f) {
1256 if (do_xauth)
1257 fprintf(f, "%s %s\n", s->auth_proto,
1258 s->auth_data);
1259 pclose(f);
1260 } else
1261 fprintf(stderr, "Could not run %s\n",
1262 _PATH_SSH_SYSTEM_RC);
1263 } else if (do_xauth && options.xauth_location != NULL) {
1264 /* Add authority data to .Xauthority if appropriate. */
1265 if (debug_flag) {
1266 fprintf(stderr,
1267 "Running %.500s remove %.100s\n",
1268 options.xauth_location, s->auth_display);
1269 fprintf(stderr,
1270 "%.500s add %.100s %.100s %.100s\n",
1271 options.xauth_location, s->auth_display,
1272 s->auth_proto, s->auth_data);
1274 snprintf(cmd, sizeof cmd, "%s -q -",
1275 options.xauth_location);
1276 f = popen(cmd, "w");
1277 if (f) {
1278 fprintf(f, "remove %s\n",
1279 s->auth_display);
1280 fprintf(f, "add %s %s %s\n",
1281 s->auth_display, s->auth_proto,
1282 s->auth_data);
1283 pclose(f);
1284 } else {
1285 fprintf(stderr, "Could not run %s\n",
1286 cmd);
1291 static void
1292 do_nologin(struct passwd *pw)
1294 FILE *f = NULL;
1295 char buf[1024];
1297 #ifdef HAVE_LOGIN_CAP
1298 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1299 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1300 _PATH_NOLOGIN), "r");
1301 #else
1302 if (pw->pw_uid)
1303 f = fopen(_PATH_NOLOGIN, "r");
1304 #endif
1305 if (f) {
1306 /* /etc/nologin exists. Print its contents and exit. */
1307 logit("User %.100s not allowed because %s exists",
1308 pw->pw_name, _PATH_NOLOGIN);
1309 while (fgets(buf, sizeof(buf), f))
1310 fputs(buf, stderr);
1311 fclose(f);
1312 fflush(NULL);
1313 exit(254);
1318 * Chroot into a directory after checking it for safety: all path components
1319 * must be root-owned directories with strict permissions.
1321 static void
1322 safely_chroot(const char *path, uid_t uid)
1324 const char *cp;
1325 char component[MAXPATHLEN];
1326 struct stat st;
1328 if (*path != '/')
1329 fatal("chroot path does not begin at root");
1330 if (strlen(path) >= sizeof(component))
1331 fatal("chroot path too long");
1334 * Descend the path, checking that each component is a
1335 * root-owned directory with strict permissions.
1337 for (cp = path; cp != NULL;) {
1338 if ((cp = strchr(cp, '/')) == NULL)
1339 strlcpy(component, path, sizeof(component));
1340 else {
1341 cp++;
1342 memcpy(component, path, cp - path);
1343 component[cp - path] = '\0';
1346 debug3("%s: checking '%s'", __func__, component);
1348 if (stat(component, &st) != 0)
1349 fatal("%s: stat(\"%s\"): %s", __func__,
1350 component, strerror(errno));
1351 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1352 fatal("bad ownership or modes for chroot "
1353 "directory %s\"%s\"",
1354 cp == NULL ? "" : "component ", component);
1355 if (!S_ISDIR(st.st_mode))
1356 fatal("chroot path %s\"%s\" is not a directory",
1357 cp == NULL ? "" : "component ", component);
1361 if (chdir(path) == -1)
1362 fatal("Unable to chdir to chroot path \"%s\": "
1363 "%s", path, strerror(errno));
1364 if (chroot(path) == -1)
1365 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1366 if (chdir("/") == -1)
1367 fatal("%s: chdir(/) after chroot: %s",
1368 __func__, strerror(errno));
1369 verbose("Changed root directory to \"%s\"", path);
1372 /* Set login name, uid, gid, and groups. */
1373 void
1374 do_setusercontext(struct passwd *pw)
1376 char *chroot_path, *tmp;
1378 #ifdef WITH_SELINUX
1379 /* Cache selinux status for later use */
1380 (void)ssh_selinux_enabled();
1381 #endif
1383 #ifndef HAVE_CYGWIN
1384 if (getuid() == 0 || geteuid() == 0)
1385 #endif /* HAVE_CYGWIN */
1388 #ifdef HAVE_SETPCRED
1389 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1390 fatal("Failed to set process credentials");
1391 #endif /* HAVE_SETPCRED */
1392 #ifdef HAVE_LOGIN_CAP
1393 # ifdef __bsdi__
1394 setpgid(0, 0);
1395 # endif
1396 # ifdef USE_PAM
1397 if (options.use_pam) {
1398 do_pam_setcred(use_privsep);
1400 # endif /* USE_PAM */
1401 if (setusercontext(lc, pw, pw->pw_uid,
1402 (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1403 perror("unable to set user context");
1404 exit(1);
1406 #else
1407 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1408 /* Sets login uid for accounting */
1409 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1410 error("setluid: %s", strerror(errno));
1411 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1413 if (setlogin(pw->pw_name) < 0)
1414 error("setlogin failed: %s", strerror(errno));
1415 if (setgid(pw->pw_gid) < 0) {
1416 perror("setgid");
1417 exit(1);
1419 /* Initialize the group list. */
1420 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1421 perror("initgroups");
1422 exit(1);
1424 endgrent();
1425 # ifdef USE_PAM
1427 * PAM credentials may take the form of supplementary groups.
1428 * These will have been wiped by the above initgroups() call.
1429 * Reestablish them here.
1431 if (options.use_pam) {
1432 do_pam_setcred(use_privsep);
1434 # endif /* USE_PAM */
1435 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1436 irix_setusercontext(pw);
1437 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1438 # ifdef _AIX
1439 aix_usrinfo(pw);
1440 # endif /* _AIX */
1441 # ifdef USE_LIBIAF
1442 if (set_id(pw->pw_name) != 0) {
1443 exit(1);
1445 # endif /* USE_LIBIAF */
1446 #endif
1448 if (options.chroot_directory != NULL &&
1449 strcasecmp(options.chroot_directory, "none") != 0) {
1450 tmp = tilde_expand_filename(options.chroot_directory,
1451 pw->pw_uid);
1452 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1453 "u", pw->pw_name, (char *)NULL);
1454 safely_chroot(chroot_path, pw->pw_uid);
1455 free(tmp);
1456 free(chroot_path);
1459 #ifdef HAVE_LOGIN_CAP
1460 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1461 perror("unable to set user context (setuser)");
1462 exit(1);
1464 #else
1465 /* Permanently switch to the desired uid. */
1466 permanently_set_uid(pw);
1467 #endif
1470 #ifdef HAVE_CYGWIN
1471 if (is_winnt)
1472 #endif
1473 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1474 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1476 #ifdef WITH_SELINUX
1477 ssh_selinux_setup_exec_context(pw->pw_name);
1478 #endif
1481 static void
1482 do_pwchange(Session *s)
1484 fflush(NULL);
1485 fprintf(stderr, "WARNING: Your password has expired.\n");
1486 if (s->ttyfd != -1) {
1487 fprintf(stderr,
1488 "You must change your password now and login again!\n");
1489 #ifdef PASSWD_NEEDS_USERNAME
1490 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1491 (char *)NULL);
1492 #else
1493 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1494 #endif
1495 perror("passwd");
1496 } else {
1497 fprintf(stderr,
1498 "Password change required but no TTY available.\n");
1500 exit(1);
1503 static void
1504 launch_login(struct passwd *pw, const char *hostname)
1506 /* Launch login(1). */
1508 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1509 #ifdef xxxLOGIN_NEEDS_TERM
1510 (s->term ? s->term : "unknown"),
1511 #endif /* LOGIN_NEEDS_TERM */
1512 #ifdef LOGIN_NO_ENDOPT
1513 "-p", "-f", pw->pw_name, (char *)NULL);
1514 #else
1515 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1516 #endif
1518 /* Login couldn't be executed, die. */
1520 perror("login");
1521 exit(1);
1524 static void
1525 child_close_fds(void)
1527 int i;
1529 if (packet_get_connection_in() == packet_get_connection_out())
1530 close(packet_get_connection_in());
1531 else {
1532 close(packet_get_connection_in());
1533 close(packet_get_connection_out());
1536 * Close all descriptors related to channels. They will still remain
1537 * open in the parent.
1539 /* XXX better use close-on-exec? -markus */
1540 channel_close_all();
1543 * Close any extra file descriptors. Note that there may still be
1544 * descriptors left by system functions. They will be closed later.
1546 endpwent();
1549 * Close any extra open file descriptors so that we don't have them
1550 * hanging around in clients. Note that we want to do this after
1551 * initgroups, because at least on Solaris 2.3 it leaves file
1552 * descriptors open.
1554 for (i = 3; i < 64; i++)
1555 close(i);
1559 * Performs common processing for the child, such as setting up the
1560 * environment, closing extra file descriptors, setting the user and group
1561 * ids, and executing the command or shell.
1563 #define ARGV_MAX 10
1564 void
1565 do_child(Session *s, const char *command)
1567 extern char **environ;
1568 char **env;
1569 char *argv[ARGV_MAX];
1570 const char *shell, *shell0, *hostname = NULL;
1571 struct passwd *pw = s->pw;
1572 #ifdef HAVE_LOGIN_CAP
1573 int lc_requirehome;
1574 #endif
1576 /* remove hostkey from the child's memory */
1577 destroy_sensitive_data();
1579 /* Force a password change */
1580 if (s->authctxt->force_pwchange) {
1581 do_setusercontext(pw);
1582 child_close_fds();
1583 do_pwchange(s);
1584 exit(1);
1587 /* login(1) is only called if we execute the login shell */
1588 if (options.use_login && command != NULL)
1589 options.use_login = 0;
1591 #ifdef _UNICOS
1592 cray_setup(pw->pw_uid, pw->pw_name, command);
1593 #endif /* _UNICOS */
1596 * Login(1) does this as well, and it needs uid 0 for the "-h"
1597 * switch, so we let login(1) to this for us.
1599 if (!options.use_login) {
1600 #ifdef HAVE_OSF_SIA
1601 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1602 if (!check_quietlogin(s, command))
1603 do_motd();
1604 #else /* HAVE_OSF_SIA */
1605 /* When PAM is enabled we rely on it to do the nologin check */
1606 if (!options.use_pam)
1607 do_nologin(pw);
1608 do_setusercontext(pw);
1610 * PAM session modules in do_setusercontext may have
1611 * generated messages, so if this in an interactive
1612 * login then display them too.
1614 if (!check_quietlogin(s, command))
1615 display_loginmsg();
1616 #endif /* HAVE_OSF_SIA */
1619 #ifdef USE_PAM
1620 if (options.use_pam && !options.use_login && !is_pam_session_open()) {
1621 debug3("PAM session not opened, exiting");
1622 display_loginmsg();
1623 exit(254);
1625 #endif
1628 * Get the shell from the password data. An empty shell field is
1629 * legal, and means /bin/sh.
1631 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1634 * Make sure $SHELL points to the shell from the password file,
1635 * even if shell is overridden from login.conf
1637 env = do_setup_env(s, shell);
1639 #ifdef HAVE_LOGIN_CAP
1640 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1641 #endif
1643 /* we have to stash the hostname before we close our socket. */
1644 if (options.use_login)
1645 hostname = get_remote_name_or_ip(utmp_len,
1646 options.use_dns);
1648 * Close the connection descriptors; note that this is the child, and
1649 * the server will still have the socket open, and it is important
1650 * that we do not shutdown it. Note that the descriptors cannot be
1651 * closed before building the environment, as we call
1652 * get_remote_ipaddr there.
1654 child_close_fds();
1657 * Must take new environment into use so that .ssh/rc,
1658 * /etc/ssh/sshrc and xauth are run in the proper environment.
1660 environ = env;
1662 #ifdef HAVE_LOGIN_CAP
1663 lc_requirehome = login_getcapbool(lc, "requirehome", 0);
1664 login_close(lc);
1665 #endif
1666 #if defined(KRB5) && defined(USE_AFS)
1668 * At this point, we check to see if AFS is active and if we have
1669 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1670 * if we can (and need to) extend the ticket into an AFS token. If
1671 * we don't do this, we run into potential problems if the user's
1672 * home directory is in AFS and it's not world-readable.
1675 if (options.kerberos_get_afs_token && k_hasafs() &&
1676 (s->authctxt->krb5_ctx != NULL)) {
1677 char cell[64];
1679 debug("Getting AFS token");
1681 k_setpag();
1683 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1684 krb5_afslog(s->authctxt->krb5_ctx,
1685 s->authctxt->krb5_fwd_ccache, cell, NULL);
1687 krb5_afslog_home(s->authctxt->krb5_ctx,
1688 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1690 #endif
1692 /* Change current directory to the user's home directory. */
1693 if (chdir(pw->pw_dir) < 0) {
1694 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1695 pw->pw_dir, strerror(errno));
1696 #ifdef HAVE_LOGIN_CAP
1697 if (lc_requirehome)
1698 exit(1);
1699 #endif
1702 closefrom(STDERR_FILENO + 1);
1704 if (!options.use_login)
1705 do_rc_files(s, shell);
1707 /* restore SIGPIPE for child */
1708 signal(SIGPIPE, SIG_DFL);
1710 if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1711 extern int optind, optreset;
1712 int i;
1713 char *p, *args;
1715 setproctitle("%s@internal-sftp-server", s->pw->pw_name);
1716 args = strdup(command ? command : "sftp-server");
1717 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1718 if (i < ARGV_MAX - 1)
1719 argv[i++] = p;
1720 argv[i] = NULL;
1721 optind = optreset = 1;
1722 __progname = argv[0];
1723 exit(sftp_server_main(i, argv, s->pw));
1726 if (options.use_login) {
1727 launch_login(pw, hostname);
1728 /* NEVERREACHED */
1731 /* Get the last component of the shell name. */
1732 if ((shell0 = strrchr(shell, '/')) != NULL)
1733 shell0++;
1734 else
1735 shell0 = shell;
1738 * If we have no command, execute the shell. In this case, the shell
1739 * name to be passed in argv[0] is preceded by '-' to indicate that
1740 * this is a login shell.
1742 if (!command) {
1743 char argv0[256];
1745 /* Start the shell. Set initial character to '-'. */
1746 argv0[0] = '-';
1748 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1749 >= sizeof(argv0) - 1) {
1750 errno = EINVAL;
1751 perror(shell);
1752 exit(1);
1755 /* Execute the shell. */
1756 argv[0] = argv0;
1757 argv[1] = NULL;
1758 execve(shell, argv, env);
1760 /* Executing the shell failed. */
1761 perror(shell);
1762 exit(1);
1765 * Execute the command using the user's shell. This uses the -c
1766 * option to execute the command.
1768 argv[0] = (char *) shell0;
1769 argv[1] = "-c";
1770 argv[2] = (char *) command;
1771 argv[3] = NULL;
1772 execve(shell, argv, env);
1773 perror(shell);
1774 exit(1);
1777 Session *
1778 session_new(void)
1780 int i;
1781 static int did_init = 0;
1782 if (!did_init) {
1783 debug("session_new: init");
1784 for (i = 0; i < MAX_SESSIONS; i++) {
1785 sessions[i].used = 0;
1787 did_init = 1;
1789 for (i = 0; i < MAX_SESSIONS; i++) {
1790 Session *s = &sessions[i];
1791 if (! s->used) {
1792 memset(s, 0, sizeof(*s));
1793 s->chanid = -1;
1794 s->ptyfd = -1;
1795 s->ttyfd = -1;
1796 s->used = 1;
1797 s->self = i;
1798 s->x11_chanids = NULL;
1799 debug("session_new: session %d", i);
1800 return s;
1803 return NULL;
1806 static void
1807 session_dump(void)
1809 int i;
1810 for (i = 0; i < MAX_SESSIONS; i++) {
1811 Session *s = &sessions[i];
1812 debug("dump: used %d session %d %p channel %d pid %ld",
1813 s->used,
1814 s->self,
1816 s->chanid,
1817 (long)s->pid);
1822 session_open(Authctxt *authctxt, int chanid)
1824 Session *s = session_new();
1825 debug("session_open: channel %d", chanid);
1826 if (s == NULL) {
1827 error("no more sessions");
1828 return 0;
1830 s->authctxt = authctxt;
1831 s->pw = authctxt->pw;
1832 if (s->pw == NULL || !authctxt->valid)
1833 fatal("no user for session %d", s->self);
1834 debug("session_open: session %d: link with channel %d", s->self, chanid);
1835 s->chanid = chanid;
1836 return 1;
1839 Session *
1840 session_by_tty(char *tty)
1842 int i;
1843 for (i = 0; i < MAX_SESSIONS; i++) {
1844 Session *s = &sessions[i];
1845 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1846 debug("session_by_tty: session %d tty %s", i, tty);
1847 return s;
1850 debug("session_by_tty: unknown tty %.100s", tty);
1851 session_dump();
1852 return NULL;
1855 static Session *
1856 session_by_channel(int id)
1858 int i;
1859 for (i = 0; i < MAX_SESSIONS; i++) {
1860 Session *s = &sessions[i];
1861 if (s->used && s->chanid == id) {
1862 debug("session_by_channel: session %d channel %d", i, id);
1863 return s;
1866 debug("session_by_channel: unknown channel %d", id);
1867 session_dump();
1868 return NULL;
1871 static Session *
1872 session_by_x11_channel(int id)
1874 int i, j;
1876 for (i = 0; i < MAX_SESSIONS; i++) {
1877 Session *s = &sessions[i];
1879 if (s->x11_chanids == NULL || !s->used)
1880 continue;
1881 for (j = 0; s->x11_chanids[j] != -1; j++) {
1882 if (s->x11_chanids[j] == id) {
1883 debug("session_by_x11_channel: session %d "
1884 "channel %d", s->self, id);
1885 return s;
1889 debug("session_by_x11_channel: unknown channel %d", id);
1890 session_dump();
1891 return NULL;
1894 static Session *
1895 session_by_pid(pid_t pid)
1897 int i;
1898 debug("session_by_pid: pid %ld", (long)pid);
1899 for (i = 0; i < MAX_SESSIONS; i++) {
1900 Session *s = &sessions[i];
1901 if (s->used && s->pid == pid)
1902 return s;
1904 error("session_by_pid: unknown pid %ld", (long)pid);
1905 session_dump();
1906 return NULL;
1909 static int
1910 session_window_change_req(Session *s)
1912 s->col = packet_get_int();
1913 s->row = packet_get_int();
1914 s->xpixel = packet_get_int();
1915 s->ypixel = packet_get_int();
1916 packet_check_eom();
1917 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1918 return 1;
1921 static int
1922 session_pty_req(Session *s)
1924 u_int len;
1925 int n_bytes;
1927 if (no_pty_flag) {
1928 debug("Allocating a pty not permitted for this authentication.");
1929 return 0;
1931 if (s->ttyfd != -1) {
1932 packet_disconnect("Protocol error: you already have a pty.");
1933 return 0;
1936 s->term = packet_get_string(&len);
1938 if (compat20) {
1939 s->col = packet_get_int();
1940 s->row = packet_get_int();
1941 } else {
1942 s->row = packet_get_int();
1943 s->col = packet_get_int();
1945 s->xpixel = packet_get_int();
1946 s->ypixel = packet_get_int();
1948 if (strcmp(s->term, "") == 0) {
1949 xfree(s->term);
1950 s->term = NULL;
1953 /* Allocate a pty and open it. */
1954 debug("Allocating pty.");
1955 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1956 if (s->term)
1957 xfree(s->term);
1958 s->term = NULL;
1959 s->ptyfd = -1;
1960 s->ttyfd = -1;
1961 error("session_pty_req: session %d alloc failed", s->self);
1962 return 0;
1964 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1966 /* for SSH1 the tty modes length is not given */
1967 if (!compat20)
1968 n_bytes = packet_remaining();
1969 tty_parse_modes(s->ttyfd, &n_bytes);
1971 if (!use_privsep)
1972 pty_setowner(s->pw, s->tty);
1974 /* Set window size from the packet. */
1975 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1977 packet_check_eom();
1978 session_proctitle(s);
1979 return 1;
1982 static int
1983 session_subsystem_req(Session *s)
1985 struct stat st;
1986 u_int len;
1987 int success = 0;
1988 char *prog, *cmd, *subsys = packet_get_string(&len);
1989 u_int i;
1991 packet_check_eom();
1992 logit("subsystem request for %.100s", subsys);
1994 for (i = 0; i < options.num_subsystems; i++) {
1995 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1996 prog = options.subsystem_command[i];
1997 cmd = options.subsystem_args[i];
1998 if (!strcmp(INTERNAL_SFTP_NAME, prog)) {
1999 s->is_subsystem = SUBSYSTEM_INT_SFTP;
2000 } else if (stat(prog, &st) < 0) {
2001 error("subsystem: cannot stat %s: %s", prog,
2002 strerror(errno));
2003 break;
2004 } else {
2005 s->is_subsystem = SUBSYSTEM_EXT;
2007 debug("subsystem: exec() %s", cmd);
2008 do_exec(s, cmd);
2009 success = 1;
2010 break;
2014 if (!success)
2015 logit("subsystem request for %.100s failed, subsystem not found",
2016 subsys);
2018 xfree(subsys);
2019 return success;
2022 static int
2023 session_x11_req(Session *s)
2025 int success;
2027 if (s->auth_proto != NULL || s->auth_data != NULL) {
2028 error("session_x11_req: session %d: "
2029 "x11 forwarding already active", s->self);
2030 return 0;
2032 s->single_connection = packet_get_char();
2033 s->auth_proto = packet_get_string(NULL);
2034 s->auth_data = packet_get_string(NULL);
2035 s->screen = packet_get_int();
2036 packet_check_eom();
2038 success = session_setup_x11fwd(s);
2039 if (!success) {
2040 xfree(s->auth_proto);
2041 xfree(s->auth_data);
2042 s->auth_proto = NULL;
2043 s->auth_data = NULL;
2045 return success;
2048 static int
2049 session_shell_req(Session *s)
2051 packet_check_eom();
2052 do_exec(s, NULL);
2053 return 1;
2056 static int
2057 session_exec_req(Session *s)
2059 u_int len;
2060 char *command = packet_get_string(&len);
2061 packet_check_eom();
2062 do_exec(s, command);
2063 xfree(command);
2064 return 1;
2067 static int
2068 session_break_req(Session *s)
2071 packet_get_int(); /* ignored */
2072 packet_check_eom();
2074 if (s->ttyfd == -1 ||
2075 tcsendbreak(s->ttyfd, 0) < 0)
2076 return 0;
2077 return 1;
2080 static int
2081 session_env_req(Session *s)
2083 char *name, *val;
2084 u_int name_len, val_len, i;
2086 name = packet_get_string(&name_len);
2087 val = packet_get_string(&val_len);
2088 packet_check_eom();
2090 /* Don't set too many environment variables */
2091 if (s->num_env > 128) {
2092 debug2("Ignoring env request %s: too many env vars", name);
2093 goto fail;
2096 for (i = 0; i < options.num_accept_env; i++) {
2097 if (match_pattern(name, options.accept_env[i])) {
2098 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2099 s->env = xrealloc(s->env, s->num_env + 1,
2100 sizeof(*s->env));
2101 s->env[s->num_env].name = name;
2102 s->env[s->num_env].val = val;
2103 s->num_env++;
2104 return (1);
2107 debug2("Ignoring env request %s: disallowed name", name);
2109 fail:
2110 xfree(name);
2111 xfree(val);
2112 return (0);
2115 static int
2116 session_auth_agent_req(Session *s)
2118 static int called = 0;
2119 packet_check_eom();
2120 if (no_agent_forwarding_flag) {
2121 debug("session_auth_agent_req: no_agent_forwarding_flag");
2122 return 0;
2124 if (called) {
2125 return 0;
2126 } else {
2127 called = 1;
2128 return auth_input_request_forwarding(s->pw);
2133 session_input_channel_req(Channel *c, const char *rtype)
2135 int success = 0;
2136 Session *s;
2138 if ((s = session_by_channel(c->self)) == NULL) {
2139 logit("session_input_channel_req: no session %d req %.100s",
2140 c->self, rtype);
2141 return 0;
2143 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2146 * a session is in LARVAL state until a shell, a command
2147 * or a subsystem is executed
2149 if (c->type == SSH_CHANNEL_LARVAL) {
2150 if (strcmp(rtype, "shell") == 0) {
2151 success = session_shell_req(s);
2152 } else if (strcmp(rtype, "exec") == 0) {
2153 success = session_exec_req(s);
2154 } else if (strcmp(rtype, "pty-req") == 0) {
2155 success = session_pty_req(s);
2156 } else if (strcmp(rtype, "x11-req") == 0) {
2157 success = session_x11_req(s);
2158 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2159 success = session_auth_agent_req(s);
2160 } else if (strcmp(rtype, "subsystem") == 0) {
2161 success = session_subsystem_req(s);
2162 } else if (strcmp(rtype, "env") == 0) {
2163 success = session_env_req(s);
2166 if (strcmp(rtype, "window-change") == 0) {
2167 success = session_window_change_req(s);
2168 } else if (strcmp(rtype, "break") == 0) {
2169 success = session_break_req(s);
2172 return success;
2175 void
2176 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2178 if (!compat20)
2179 fatal("session_set_fds: called for proto != 2.0");
2181 * now that have a child and a pipe to the child,
2182 * we can activate our channel and register the fd's
2184 if (s->chanid == -1)
2185 fatal("no channel for session %d", s->self);
2186 channel_set_fds(s->chanid,
2187 fdout, fdin, fderr,
2188 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2190 CHAN_SES_WINDOW_DEFAULT);
2194 * Function to perform pty cleanup. Also called if we get aborted abnormally
2195 * (e.g., due to a dropped connection).
2197 void
2198 session_pty_cleanup2(Session *s)
2200 if (s == NULL) {
2201 error("session_pty_cleanup: no session");
2202 return;
2204 if (s->ttyfd == -1)
2205 return;
2207 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2209 /* Record that the user has logged out. */
2210 if (s->pid != 0)
2211 record_logout(s->pid, s->tty, s->pw->pw_name);
2213 /* Release the pseudo-tty. */
2214 if (getuid() == 0)
2215 pty_release(s->tty);
2218 * Close the server side of the socket pairs. We must do this after
2219 * the pty cleanup, so that another process doesn't get this pty
2220 * while we're still cleaning up.
2222 if (close(s->ptymaster) < 0)
2223 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2225 /* unlink pty from session */
2226 s->ttyfd = -1;
2229 void
2230 session_pty_cleanup(Session *s)
2232 PRIVSEP(session_pty_cleanup2(s));
2235 static char *
2236 sig2name(int sig)
2238 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2239 SSH_SIG(ABRT);
2240 SSH_SIG(ALRM);
2241 SSH_SIG(FPE);
2242 SSH_SIG(HUP);
2243 SSH_SIG(ILL);
2244 SSH_SIG(INT);
2245 SSH_SIG(KILL);
2246 SSH_SIG(PIPE);
2247 SSH_SIG(QUIT);
2248 SSH_SIG(SEGV);
2249 SSH_SIG(TERM);
2250 SSH_SIG(USR1);
2251 SSH_SIG(USR2);
2252 #undef SSH_SIG
2253 return "SIG@openssh.com";
2256 static void
2257 session_close_x11(int id)
2259 Channel *c;
2261 if ((c = channel_by_id(id)) == NULL) {
2262 debug("session_close_x11: x11 channel %d missing", id);
2263 } else {
2264 /* Detach X11 listener */
2265 debug("session_close_x11: detach x11 channel %d", id);
2266 channel_cancel_cleanup(id);
2267 if (c->ostate != CHAN_OUTPUT_CLOSED)
2268 chan_mark_dead(c);
2272 static void
2273 session_close_single_x11(int id, void *arg)
2275 Session *s;
2276 u_int i;
2278 debug3("session_close_single_x11: channel %d", id);
2279 channel_cancel_cleanup(id);
2280 if ((s = session_by_x11_channel(id)) == NULL)
2281 fatal("session_close_single_x11: no x11 channel %d", id);
2282 for (i = 0; s->x11_chanids[i] != -1; i++) {
2283 debug("session_close_single_x11: session %d: "
2284 "closing channel %d", s->self, s->x11_chanids[i]);
2286 * The channel "id" is already closing, but make sure we
2287 * close all of its siblings.
2289 if (s->x11_chanids[i] != id)
2290 session_close_x11(s->x11_chanids[i]);
2292 xfree(s->x11_chanids);
2293 s->x11_chanids = NULL;
2294 if (s->display) {
2295 xfree(s->display);
2296 s->display = NULL;
2298 if (s->auth_proto) {
2299 xfree(s->auth_proto);
2300 s->auth_proto = NULL;
2302 if (s->auth_data) {
2303 xfree(s->auth_data);
2304 s->auth_data = NULL;
2306 if (s->auth_display) {
2307 xfree(s->auth_display);
2308 s->auth_display = NULL;
2312 static void
2313 session_exit_message(Session *s, int status)
2315 Channel *c;
2317 if ((c = channel_lookup(s->chanid)) == NULL)
2318 fatal("session_exit_message: session %d: no channel %d",
2319 s->self, s->chanid);
2320 debug("session_exit_message: session %d channel %d pid %ld",
2321 s->self, s->chanid, (long)s->pid);
2323 if (WIFEXITED(status)) {
2324 channel_request_start(s->chanid, "exit-status", 0);
2325 packet_put_int(WEXITSTATUS(status));
2326 packet_send();
2327 } else if (WIFSIGNALED(status)) {
2328 channel_request_start(s->chanid, "exit-signal", 0);
2329 packet_put_cstring(sig2name(WTERMSIG(status)));
2330 #ifdef WCOREDUMP
2331 packet_put_char(WCOREDUMP(status)? 1 : 0);
2332 #else /* WCOREDUMP */
2333 packet_put_char(0);
2334 #endif /* WCOREDUMP */
2335 packet_put_cstring("");
2336 packet_put_cstring("");
2337 packet_send();
2338 } else {
2339 /* Some weird exit cause. Just exit. */
2340 packet_disconnect("wait returned status %04x.", status);
2343 /* disconnect channel */
2344 debug("session_exit_message: release channel %d", s->chanid);
2347 * Adjust cleanup callback attachment to send close messages when
2348 * the channel gets EOF. The session will be then be closed
2349 * by session_close_by_channel when the childs close their fds.
2351 channel_register_cleanup(c->self, session_close_by_channel, 1);
2354 * emulate a write failure with 'chan_write_failed', nobody will be
2355 * interested in data we write.
2356 * Note that we must not call 'chan_read_failed', since there could
2357 * be some more data waiting in the pipe.
2359 if (c->ostate != CHAN_OUTPUT_CLOSED)
2360 chan_write_failed(c);
2363 void
2364 session_close(Session *s)
2366 u_int i;
2368 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2369 if (s->ttyfd != -1)
2370 session_pty_cleanup(s);
2371 if (s->term)
2372 xfree(s->term);
2373 if (s->display)
2374 xfree(s->display);
2375 if (s->x11_chanids)
2376 xfree(s->x11_chanids);
2377 if (s->auth_display)
2378 xfree(s->auth_display);
2379 if (s->auth_data)
2380 xfree(s->auth_data);
2381 if (s->auth_proto)
2382 xfree(s->auth_proto);
2383 s->used = 0;
2384 if (s->env != NULL) {
2385 for (i = 0; i < s->num_env; i++) {
2386 xfree(s->env[i].name);
2387 xfree(s->env[i].val);
2389 xfree(s->env);
2391 session_proctitle(s);
2394 void
2395 session_close_by_pid(pid_t pid, int status)
2397 Session *s = session_by_pid(pid);
2398 if (s == NULL) {
2399 debug("session_close_by_pid: no session for pid %ld",
2400 (long)pid);
2401 return;
2403 if (s->chanid != -1)
2404 session_exit_message(s, status);
2405 if (s->ttyfd != -1)
2406 session_pty_cleanup(s);
2407 s->pid = 0;
2411 * this is called when a channel dies before
2412 * the session 'child' itself dies
2414 void
2415 session_close_by_channel(int id, void *arg)
2417 Session *s = session_by_channel(id);
2418 u_int i;
2420 if (s == NULL) {
2421 debug("session_close_by_channel: no session for id %d", id);
2422 return;
2424 debug("session_close_by_channel: channel %d child %ld",
2425 id, (long)s->pid);
2426 if (s->pid != 0) {
2427 debug("session_close_by_channel: channel %d: has child", id);
2429 * delay detach of session, but release pty, since
2430 * the fd's to the child are already closed
2432 if (s->ttyfd != -1)
2433 session_pty_cleanup(s);
2434 return;
2436 /* detach by removing callback */
2437 channel_cancel_cleanup(s->chanid);
2439 /* Close any X11 listeners associated with this session */
2440 if (s->x11_chanids != NULL) {
2441 for (i = 0; s->x11_chanids[i] != -1; i++) {
2442 session_close_x11(s->x11_chanids[i]);
2443 s->x11_chanids[i] = -1;
2447 s->chanid = -1;
2448 session_close(s);
2451 void
2452 session_destroy_all(void (*closefunc)(Session *))
2454 int i;
2455 for (i = 0; i < MAX_SESSIONS; i++) {
2456 Session *s = &sessions[i];
2457 if (s->used) {
2458 if (closefunc != NULL)
2459 closefunc(s);
2460 else
2461 session_close(s);
2466 static char *
2467 session_tty_list(void)
2469 static char buf[1024];
2470 int i;
2471 char *cp;
2473 buf[0] = '\0';
2474 for (i = 0; i < MAX_SESSIONS; i++) {
2475 Session *s = &sessions[i];
2476 if (s->used && s->ttyfd != -1) {
2478 if (strncmp(s->tty, "/dev/", 5) != 0) {
2479 cp = strrchr(s->tty, '/');
2480 cp = (cp == NULL) ? s->tty : cp + 1;
2481 } else
2482 cp = s->tty + 5;
2484 if (buf[0] != '\0')
2485 strlcat(buf, ",", sizeof buf);
2486 strlcat(buf, cp, sizeof buf);
2489 if (buf[0] == '\0')
2490 strlcpy(buf, "notty", sizeof buf);
2491 return buf;
2494 void
2495 session_proctitle(Session *s)
2497 if (s->pw == NULL)
2498 error("no user for session %d", s->self);
2499 else
2500 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2504 session_setup_x11fwd(Session *s)
2506 struct stat st;
2507 char display[512], auth_display[512];
2508 char hostname[MAXHOSTNAMELEN];
2509 u_int i;
2511 if (no_x11_forwarding_flag) {
2512 packet_send_debug("X11 forwarding disabled in user configuration file.");
2513 return 0;
2515 if (!options.x11_forwarding) {
2516 debug("X11 forwarding disabled in server configuration file.");
2517 return 0;
2519 if (!options.xauth_location ||
2520 (stat(options.xauth_location, &st) == -1)) {
2521 packet_send_debug("No xauth program; cannot forward with spoofing.");
2522 return 0;
2524 if (options.use_login) {
2525 packet_send_debug("X11 forwarding disabled; "
2526 "not compatible with UseLogin=yes.");
2527 return 0;
2529 if (s->display != NULL) {
2530 debug("X11 display already set.");
2531 return 0;
2533 if (x11_create_display_inet(options.x11_display_offset,
2534 options.x11_use_localhost, s->single_connection,
2535 &s->display_number, &s->x11_chanids) == -1) {
2536 debug("x11_create_display_inet failed.");
2537 return 0;
2539 for (i = 0; s->x11_chanids[i] != -1; i++) {
2540 channel_register_cleanup(s->x11_chanids[i],
2541 session_close_single_x11, 0);
2544 /* Set up a suitable value for the DISPLAY variable. */
2545 if (gethostname(hostname, sizeof(hostname)) < 0)
2546 fatal("gethostname: %.100s", strerror(errno));
2548 * auth_display must be used as the displayname when the
2549 * authorization entry is added with xauth(1). This will be
2550 * different than the DISPLAY string for localhost displays.
2552 if (options.x11_use_localhost) {
2553 snprintf(display, sizeof display, "localhost:%u.%u",
2554 s->display_number, s->screen);
2555 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2556 s->display_number, s->screen);
2557 s->display = xstrdup(display);
2558 s->auth_display = xstrdup(auth_display);
2559 } else {
2560 #ifdef IPADDR_IN_DISPLAY
2561 struct hostent *he;
2562 struct in_addr my_addr;
2564 he = gethostbyname(hostname);
2565 if (he == NULL) {
2566 error("Can't get IP address for X11 DISPLAY.");
2567 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2568 return 0;
2570 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2571 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2572 s->display_number, s->screen);
2573 #else
2574 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2575 s->display_number, s->screen);
2576 #endif
2577 s->display = xstrdup(display);
2578 s->auth_display = xstrdup(display);
2581 return 1;
2584 static void
2585 do_authenticated2(Authctxt *authctxt)
2587 server_loop2(authctxt);
2590 void
2591 do_cleanup(Authctxt *authctxt)
2593 static int called = 0;
2595 debug("do_cleanup");
2597 /* no cleanup if we're in the child for login shell */
2598 if (is_child)
2599 return;
2601 /* avoid double cleanup */
2602 if (called)
2603 return;
2604 called = 1;
2606 if (authctxt == NULL)
2607 return;
2609 #ifdef USE_PAM
2610 if (options.use_pam) {
2611 sshpam_cleanup();
2612 sshpam_thread_cleanup();
2614 #endif
2616 if (!authctxt->authenticated)
2617 return;
2619 #ifdef KRB5
2620 if (options.kerberos_ticket_cleanup &&
2621 authctxt->krb5_ctx)
2622 krb5_cleanup_proc(authctxt);
2623 #endif
2625 #ifdef GSSAPI
2626 if (compat20 && options.gss_cleanup_creds)
2627 ssh_gssapi_cleanup_creds();
2628 #endif
2630 /* remove agent socket */
2631 auth_sock_cleanup_proc(authctxt->pw);
2634 * Cleanup ptys/utmp only if privsep is disabled,
2635 * or if running in monitor.
2637 if (!use_privsep || mm_is_monitor())
2638 session_destroy_all(session_pty_cleanup2);