- (dtucker) [openbsd-compat/fake-rfc2553.h] rename ssh_gai_strerror hack
[openssh-git.git] / session.c
blob545e27fb78fd0c2fef1dbdef7e1c409d96449939
1 /* $OpenBSD: session.c,v 1.227 2008/02/10 10:54:29 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 /* Magic name for internal sftp-server */
98 #define INTERNAL_SFTP_NAME "internal-sftp"
100 /* func */
102 Session *session_new(void);
103 void session_set_fds(Session *, int, int, int);
104 void session_pty_cleanup(Session *);
105 void session_proctitle(Session *);
106 int session_setup_x11fwd(Session *);
107 void do_exec_pty(Session *, const char *);
108 void do_exec_no_pty(Session *, const char *);
109 void do_exec(Session *, const char *);
110 void do_login(Session *, const char *);
111 #ifdef LOGIN_NEEDS_UTMPX
112 static void do_pre_login(Session *s);
113 #endif
114 void do_child(Session *, const char *);
115 void do_motd(void);
116 int check_quietlogin(Session *, const char *);
118 static void do_authenticated1(Authctxt *);
119 static void do_authenticated2(Authctxt *);
121 static int session_pty_req(Session *);
123 /* import */
124 extern ServerOptions options;
125 extern char *__progname;
126 extern int log_stderr;
127 extern int debug_flag;
128 extern u_int utmp_len;
129 extern int startup_pipe;
130 extern void destroy_sensitive_data(void);
131 extern Buffer loginmsg;
133 /* original command from peer. */
134 const char *original_command = NULL;
136 /* data */
137 #define MAX_SESSIONS 20
138 Session sessions[MAX_SESSIONS];
140 #define SUBSYSTEM_NONE 0
141 #define SUBSYSTEM_EXT 1
142 #define SUBSYSTEM_INT_SFTP 2
144 #ifdef HAVE_LOGIN_CAP
145 login_cap_t *lc;
146 #endif
148 static int is_child = 0;
150 /* Name and directory of socket for authentication agent forwarding. */
151 static char *auth_sock_name = NULL;
152 static char *auth_sock_dir = NULL;
154 /* removes the agent forwarding socket */
156 static void
157 auth_sock_cleanup_proc(struct passwd *pw)
159 if (auth_sock_name != NULL) {
160 temporarily_use_uid(pw);
161 unlink(auth_sock_name);
162 rmdir(auth_sock_dir);
163 auth_sock_name = NULL;
164 restore_uid();
168 static int
169 auth_input_request_forwarding(struct passwd * pw)
171 Channel *nc;
172 int sock;
173 struct sockaddr_un sunaddr;
175 if (auth_sock_name != NULL) {
176 error("authentication forwarding requested twice.");
177 return 0;
180 /* Temporarily drop privileged uid for mkdir/bind. */
181 temporarily_use_uid(pw);
183 /* Allocate a buffer for the socket name, and format the name. */
184 auth_sock_name = xmalloc(MAXPATHLEN);
185 auth_sock_dir = xmalloc(MAXPATHLEN);
186 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
188 /* Create private directory for socket */
189 if (mkdtemp(auth_sock_dir) == NULL) {
190 packet_send_debug("Agent forwarding disabled: "
191 "mkdtemp() failed: %.100s", strerror(errno));
192 restore_uid();
193 xfree(auth_sock_name);
194 xfree(auth_sock_dir);
195 auth_sock_name = NULL;
196 auth_sock_dir = NULL;
197 return 0;
199 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
200 auth_sock_dir, (long) getpid());
202 /* Create the socket. */
203 sock = socket(AF_UNIX, SOCK_STREAM, 0);
204 if (sock < 0)
205 packet_disconnect("socket: %.100s", strerror(errno));
207 /* Bind it to the name. */
208 memset(&sunaddr, 0, sizeof(sunaddr));
209 sunaddr.sun_family = AF_UNIX;
210 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
212 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0)
213 packet_disconnect("bind: %.100s", strerror(errno));
215 /* Restore the privileged uid. */
216 restore_uid();
218 /* Start listening on the socket. */
219 if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
220 packet_disconnect("listen: %.100s", strerror(errno));
222 /* Allocate a channel for the authentication agent socket. */
223 nc = channel_new("auth socket",
224 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
225 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
226 0, "auth socket", 1);
227 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
228 return 1;
231 static void
232 display_loginmsg(void)
234 if (buffer_len(&loginmsg) > 0) {
235 buffer_append(&loginmsg, "\0", 1);
236 printf("%s", (char *)buffer_ptr(&loginmsg));
237 buffer_clear(&loginmsg);
241 void
242 do_authenticated(Authctxt *authctxt)
244 setproctitle("%s", authctxt->pw->pw_name);
246 /* setup the channel layer */
247 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
248 channel_permit_all_opens();
250 if (compat20)
251 do_authenticated2(authctxt);
252 else
253 do_authenticated1(authctxt);
255 do_cleanup(authctxt);
259 * Prepares for an interactive session. This is called after the user has
260 * been successfully authenticated. During this message exchange, pseudo
261 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
262 * are requested, etc.
264 static void
265 do_authenticated1(Authctxt *authctxt)
267 Session *s;
268 char *command;
269 int success, type, screen_flag;
270 int enable_compression_after_reply = 0;
271 u_int proto_len, data_len, dlen, compression_level = 0;
273 s = session_new();
274 if (s == NULL) {
275 error("no more sessions");
276 return;
278 s->authctxt = authctxt;
279 s->pw = authctxt->pw;
282 * We stay in this loop until the client requests to execute a shell
283 * or a command.
285 for (;;) {
286 success = 0;
288 /* Get a packet from the client. */
289 type = packet_read();
291 /* Process the packet. */
292 switch (type) {
293 case SSH_CMSG_REQUEST_COMPRESSION:
294 compression_level = packet_get_int();
295 packet_check_eom();
296 if (compression_level < 1 || compression_level > 9) {
297 packet_send_debug("Received invalid compression level %d.",
298 compression_level);
299 break;
301 if (options.compression == COMP_NONE) {
302 debug2("compression disabled");
303 break;
305 /* Enable compression after we have responded with SUCCESS. */
306 enable_compression_after_reply = 1;
307 success = 1;
308 break;
310 case SSH_CMSG_REQUEST_PTY:
311 success = session_pty_req(s);
312 break;
314 case SSH_CMSG_X11_REQUEST_FORWARDING:
315 s->auth_proto = packet_get_string(&proto_len);
316 s->auth_data = packet_get_string(&data_len);
318 screen_flag = packet_get_protocol_flags() &
319 SSH_PROTOFLAG_SCREEN_NUMBER;
320 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
322 if (packet_remaining() == 4) {
323 if (!screen_flag)
324 debug2("Buggy client: "
325 "X11 screen flag missing");
326 s->screen = packet_get_int();
327 } else {
328 s->screen = 0;
330 packet_check_eom();
331 success = session_setup_x11fwd(s);
332 if (!success) {
333 xfree(s->auth_proto);
334 xfree(s->auth_data);
335 s->auth_proto = NULL;
336 s->auth_data = NULL;
338 break;
340 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
341 if (no_agent_forwarding_flag || compat13) {
342 debug("Authentication agent forwarding not permitted for this authentication.");
343 break;
345 debug("Received authentication agent forwarding request.");
346 success = auth_input_request_forwarding(s->pw);
347 break;
349 case SSH_CMSG_PORT_FORWARD_REQUEST:
350 if (no_port_forwarding_flag) {
351 debug("Port forwarding not permitted for this authentication.");
352 break;
354 if (!options.allow_tcp_forwarding) {
355 debug("Port forwarding not permitted.");
356 break;
358 debug("Received TCP/IP port forwarding request.");
359 if (channel_input_port_forward_request(s->pw->pw_uid == 0,
360 options.gateway_ports) < 0) {
361 debug("Port forwarding failed.");
362 break;
364 success = 1;
365 break;
367 case SSH_CMSG_MAX_PACKET_SIZE:
368 if (packet_set_maxsize(packet_get_int()) > 0)
369 success = 1;
370 break;
372 case SSH_CMSG_EXEC_SHELL:
373 case SSH_CMSG_EXEC_CMD:
374 if (type == SSH_CMSG_EXEC_CMD) {
375 command = packet_get_string(&dlen);
376 debug("Exec command '%.500s'", command);
377 do_exec(s, command);
378 xfree(command);
379 } else {
380 do_exec(s, NULL);
382 packet_check_eom();
383 session_close(s);
384 return;
386 default:
388 * Any unknown messages in this phase are ignored,
389 * and a failure message is returned.
391 logit("Unknown packet type received after authentication: %d", type);
393 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
394 packet_send();
395 packet_write_wait();
397 /* Enable compression now that we have replied if appropriate. */
398 if (enable_compression_after_reply) {
399 enable_compression_after_reply = 0;
400 packet_start_compression(compression_level);
406 * This is called to fork and execute a command when we have no tty. This
407 * will call do_child from the child, and server_loop from the parent after
408 * setting up file descriptors and such.
410 void
411 do_exec_no_pty(Session *s, const char *command)
413 pid_t pid;
415 #ifdef USE_PIPES
416 int pin[2], pout[2], perr[2];
417 /* Allocate pipes for communicating with the program. */
418 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
419 packet_disconnect("Could not create pipes: %.100s",
420 strerror(errno));
421 #else /* USE_PIPES */
422 int inout[2], err[2];
423 /* Uses socket pairs to communicate with the program. */
424 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
425 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
426 packet_disconnect("Could not create socket pairs: %.100s",
427 strerror(errno));
428 #endif /* USE_PIPES */
429 if (s == NULL)
430 fatal("do_exec_no_pty: no session");
432 session_proctitle(s);
434 #if defined(USE_PAM)
435 if (options.use_pam && !use_privsep)
436 do_pam_setcred(1);
437 #endif /* USE_PAM */
439 /* Fork the child. */
440 if ((pid = fork()) == 0) {
441 is_child = 1;
443 /* Child. Reinitialize the log since the pid has changed. */
444 log_init(__progname, options.log_level, options.log_facility, log_stderr);
447 * Create a new session and process group since the 4.4BSD
448 * setlogin() affects the entire process group.
450 if (setsid() < 0)
451 error("setsid failed: %.100s", strerror(errno));
453 #ifdef USE_PIPES
455 * Redirect stdin. We close the parent side of the socket
456 * pair, and make the child side the standard input.
458 close(pin[1]);
459 if (dup2(pin[0], 0) < 0)
460 perror("dup2 stdin");
461 close(pin[0]);
463 /* Redirect stdout. */
464 close(pout[0]);
465 if (dup2(pout[1], 1) < 0)
466 perror("dup2 stdout");
467 close(pout[1]);
469 /* Redirect stderr. */
470 close(perr[0]);
471 if (dup2(perr[1], 2) < 0)
472 perror("dup2 stderr");
473 close(perr[1]);
474 #else /* USE_PIPES */
476 * Redirect stdin, stdout, and stderr. Stdin and stdout will
477 * use the same socket, as some programs (particularly rdist)
478 * seem to depend on it.
480 close(inout[1]);
481 close(err[1]);
482 if (dup2(inout[0], 0) < 0) /* stdin */
483 perror("dup2 stdin");
484 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
485 perror("dup2 stdout");
486 if (dup2(err[0], 2) < 0) /* stderr */
487 perror("dup2 stderr");
488 #endif /* USE_PIPES */
490 #ifdef _UNICOS
491 cray_init_job(s->pw); /* set up cray jid and tmpdir */
492 #endif
494 /* Do processing for the child (exec command etc). */
495 do_child(s, command);
496 /* NOTREACHED */
498 #ifdef _UNICOS
499 signal(WJSIGNAL, cray_job_termination_handler);
500 #endif /* _UNICOS */
501 #ifdef HAVE_CYGWIN
502 if (is_winnt)
503 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
504 #endif
505 if (pid < 0)
506 packet_disconnect("fork failed: %.100s", strerror(errno));
507 s->pid = pid;
508 /* Set interactive/non-interactive mode. */
509 packet_set_interactive(s->display != NULL);
510 #ifdef USE_PIPES
511 /* We are the parent. Close the child sides of the pipes. */
512 close(pin[0]);
513 close(pout[1]);
514 close(perr[1]);
516 if (compat20) {
517 if (s->is_subsystem) {
518 close(perr[0]);
519 perr[0] = -1;
521 session_set_fds(s, pin[1], pout[0], perr[0]);
522 } else {
523 /* Enter the interactive session. */
524 server_loop(pid, pin[1], pout[0], perr[0]);
525 /* server_loop has closed pin[1], pout[0], and perr[0]. */
527 #else /* USE_PIPES */
528 /* We are the parent. Close the child sides of the socket pairs. */
529 close(inout[0]);
530 close(err[0]);
533 * Clear loginmsg, since it's the child's responsibility to display
534 * it to the user, otherwise multiple sessions may accumulate
535 * multiple copies of the login messages.
537 buffer_clear(&loginmsg);
540 * Enter the interactive session. Note: server_loop must be able to
541 * handle the case that fdin and fdout are the same.
543 if (compat20) {
544 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
545 } else {
546 server_loop(pid, inout[1], inout[1], err[1]);
547 /* server_loop has closed inout[1] and err[1]. */
549 #endif /* USE_PIPES */
553 * This is called to fork and execute a command when we have a tty. This
554 * will call do_child from the child, and server_loop from the parent after
555 * setting up file descriptors, controlling tty, updating wtmp, utmp,
556 * lastlog, and other such operations.
558 void
559 do_exec_pty(Session *s, const char *command)
561 int fdout, ptyfd, ttyfd, ptymaster;
562 pid_t pid;
564 if (s == NULL)
565 fatal("do_exec_pty: no session");
566 ptyfd = s->ptyfd;
567 ttyfd = s->ttyfd;
569 #if defined(USE_PAM)
570 if (options.use_pam) {
571 do_pam_set_tty(s->tty);
572 if (!use_privsep)
573 do_pam_setcred(1);
575 #endif
577 /* Fork the child. */
578 if ((pid = fork()) == 0) {
579 is_child = 1;
581 /* Child. Reinitialize the log because the pid has changed. */
582 log_init(__progname, options.log_level, options.log_facility, log_stderr);
583 /* Close the master side of the pseudo tty. */
584 close(ptyfd);
586 /* Make the pseudo tty our controlling tty. */
587 pty_make_controlling_tty(&ttyfd, s->tty);
589 /* Redirect stdin/stdout/stderr from the pseudo tty. */
590 if (dup2(ttyfd, 0) < 0)
591 error("dup2 stdin: %s", strerror(errno));
592 if (dup2(ttyfd, 1) < 0)
593 error("dup2 stdout: %s", strerror(errno));
594 if (dup2(ttyfd, 2) < 0)
595 error("dup2 stderr: %s", strerror(errno));
597 /* Close the extra descriptor for the pseudo tty. */
598 close(ttyfd);
600 /* record login, etc. similar to login(1) */
601 #ifndef HAVE_OSF_SIA
602 if (!(options.use_login && command == NULL)) {
603 #ifdef _UNICOS
604 cray_init_job(s->pw); /* set up cray jid and tmpdir */
605 #endif /* _UNICOS */
606 do_login(s, command);
608 # ifdef LOGIN_NEEDS_UTMPX
609 else
610 do_pre_login(s);
611 # endif
612 #endif
614 /* Do common processing for the child, such as execing the command. */
615 do_child(s, command);
616 /* NOTREACHED */
618 #ifdef _UNICOS
619 signal(WJSIGNAL, cray_job_termination_handler);
620 #endif /* _UNICOS */
621 #ifdef HAVE_CYGWIN
622 if (is_winnt)
623 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
624 #endif
625 if (pid < 0)
626 packet_disconnect("fork failed: %.100s", strerror(errno));
627 s->pid = pid;
629 /* Parent. Close the slave side of the pseudo tty. */
630 close(ttyfd);
633 * Create another descriptor of the pty master side for use as the
634 * standard input. We could use the original descriptor, but this
635 * simplifies code in server_loop. The descriptor is bidirectional.
637 fdout = dup(ptyfd);
638 if (fdout < 0)
639 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
641 /* we keep a reference to the pty master */
642 ptymaster = dup(ptyfd);
643 if (ptymaster < 0)
644 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
645 s->ptymaster = ptymaster;
647 /* Enter interactive session. */
648 packet_set_interactive(1);
649 if (compat20) {
650 session_set_fds(s, ptyfd, fdout, -1);
651 } else {
652 server_loop(pid, ptyfd, fdout, -1);
653 /* server_loop _has_ closed ptyfd and fdout. */
657 #ifdef LOGIN_NEEDS_UTMPX
658 static void
659 do_pre_login(Session *s)
661 socklen_t fromlen;
662 struct sockaddr_storage from;
663 pid_t pid = getpid();
666 * Get IP address of client. If the connection is not a socket, let
667 * the address be 0.0.0.0.
669 memset(&from, 0, sizeof(from));
670 fromlen = sizeof(from);
671 if (packet_connection_is_on_socket()) {
672 if (getpeername(packet_get_connection_in(),
673 (struct sockaddr *)&from, &fromlen) < 0) {
674 debug("getpeername: %.100s", strerror(errno));
675 cleanup_exit(255);
679 record_utmp_only(pid, s->tty, s->pw->pw_name,
680 get_remote_name_or_ip(utmp_len, options.use_dns),
681 (struct sockaddr *)&from, fromlen);
683 #endif
686 * This is called to fork and execute a command. If another command is
687 * to be forced, execute that instead.
689 void
690 do_exec(Session *s, const char *command)
692 if (options.adm_forced_command) {
693 original_command = command;
694 command = options.adm_forced_command;
695 if (strcmp(INTERNAL_SFTP_NAME, command) == 0)
696 s->is_subsystem = SUBSYSTEM_INT_SFTP;
697 else if (s->is_subsystem)
698 s->is_subsystem = SUBSYSTEM_EXT;
699 debug("Forced command (config) '%.900s'", command);
700 } else if (forced_command) {
701 original_command = command;
702 command = forced_command;
703 if (strcmp(INTERNAL_SFTP_NAME, command) == 0)
704 s->is_subsystem = SUBSYSTEM_INT_SFTP;
705 else if (s->is_subsystem)
706 s->is_subsystem = SUBSYSTEM_EXT;
707 debug("Forced command (key option) '%.900s'", command);
710 #ifdef SSH_AUDIT_EVENTS
711 if (command != NULL)
712 PRIVSEP(audit_run_command(command));
713 else if (s->ttyfd == -1) {
714 char *shell = s->pw->pw_shell;
716 if (shell[0] == '\0') /* empty shell means /bin/sh */
717 shell =_PATH_BSHELL;
718 PRIVSEP(audit_run_command(shell));
720 #endif
721 if (s->ttyfd != -1)
722 do_exec_pty(s, command);
723 else
724 do_exec_no_pty(s, command);
726 original_command = NULL;
729 * Clear loginmsg: it's the child's responsibility to display
730 * it to the user, otherwise multiple sessions may accumulate
731 * multiple copies of the login messages.
733 buffer_clear(&loginmsg);
736 /* administrative, login(1)-like work */
737 void
738 do_login(Session *s, const char *command)
740 socklen_t fromlen;
741 struct sockaddr_storage from;
742 struct passwd * pw = s->pw;
743 pid_t pid = getpid();
746 * Get IP address of client. If the connection is not a socket, let
747 * the address be 0.0.0.0.
749 memset(&from, 0, sizeof(from));
750 fromlen = sizeof(from);
751 if (packet_connection_is_on_socket()) {
752 if (getpeername(packet_get_connection_in(),
753 (struct sockaddr *) & from, &fromlen) < 0) {
754 debug("getpeername: %.100s", strerror(errno));
755 cleanup_exit(255);
759 /* Record that there was a login on that tty from the remote host. */
760 if (!use_privsep)
761 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
762 get_remote_name_or_ip(utmp_len,
763 options.use_dns),
764 (struct sockaddr *)&from, fromlen);
766 #ifdef USE_PAM
768 * If password change is needed, do it now.
769 * This needs to occur before the ~/.hushlogin check.
771 if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
772 display_loginmsg();
773 do_pam_chauthtok();
774 s->authctxt->force_pwchange = 0;
775 /* XXX - signal [net] parent to enable forwardings */
777 #endif
779 if (check_quietlogin(s, command))
780 return;
782 display_loginmsg();
784 do_motd();
788 * Display the message of the day.
790 void
791 do_motd(void)
793 FILE *f;
794 char buf[256];
796 if (options.print_motd) {
797 #ifdef HAVE_LOGIN_CAP
798 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
799 "/etc/motd"), "r");
800 #else
801 f = fopen("/etc/motd", "r");
802 #endif
803 if (f) {
804 while (fgets(buf, sizeof(buf), f))
805 fputs(buf, stdout);
806 fclose(f);
813 * Check for quiet login, either .hushlogin or command given.
816 check_quietlogin(Session *s, const char *command)
818 char buf[256];
819 struct passwd *pw = s->pw;
820 struct stat st;
822 /* Return 1 if .hushlogin exists or a command given. */
823 if (command != NULL)
824 return 1;
825 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
826 #ifdef HAVE_LOGIN_CAP
827 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
828 return 1;
829 #else
830 if (stat(buf, &st) >= 0)
831 return 1;
832 #endif
833 return 0;
837 * Sets the value of the given variable in the environment. If the variable
838 * already exists, its value is overriden.
840 void
841 child_set_env(char ***envp, u_int *envsizep, const char *name,
842 const char *value)
844 char **env;
845 u_int envsize;
846 u_int i, namelen;
849 * If we're passed an uninitialized list, allocate a single null
850 * entry before continuing.
852 if (*envp == NULL && *envsizep == 0) {
853 *envp = xmalloc(sizeof(char *));
854 *envp[0] = NULL;
855 *envsizep = 1;
859 * Find the slot where the value should be stored. If the variable
860 * already exists, we reuse the slot; otherwise we append a new slot
861 * at the end of the array, expanding if necessary.
863 env = *envp;
864 namelen = strlen(name);
865 for (i = 0; env[i]; i++)
866 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
867 break;
868 if (env[i]) {
869 /* Reuse the slot. */
870 xfree(env[i]);
871 } else {
872 /* New variable. Expand if necessary. */
873 envsize = *envsizep;
874 if (i >= envsize - 1) {
875 if (envsize >= 1000)
876 fatal("child_set_env: too many env vars");
877 envsize += 50;
878 env = (*envp) = xrealloc(env, envsize, sizeof(char *));
879 *envsizep = envsize;
881 /* Need to set the NULL pointer at end of array beyond the new slot. */
882 env[i + 1] = NULL;
885 /* Allocate space and format the variable in the appropriate slot. */
886 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
887 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
891 * Reads environment variables from the given file and adds/overrides them
892 * into the environment. If the file does not exist, this does nothing.
893 * Otherwise, it must consist of empty lines, comments (line starts with '#')
894 * and assignments of the form name=value. No other forms are allowed.
896 static void
897 read_environment_file(char ***env, u_int *envsize,
898 const char *filename)
900 FILE *f;
901 char buf[4096];
902 char *cp, *value;
903 u_int lineno = 0;
905 f = fopen(filename, "r");
906 if (!f)
907 return;
909 while (fgets(buf, sizeof(buf), f)) {
910 if (++lineno > 1000)
911 fatal("Too many lines in environment file %s", filename);
912 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
914 if (!*cp || *cp == '#' || *cp == '\n')
915 continue;
917 cp[strcspn(cp, "\n")] = '\0';
919 value = strchr(cp, '=');
920 if (value == NULL) {
921 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
922 filename);
923 continue;
926 * Replace the equals sign by nul, and advance value to
927 * the value string.
929 *value = '\0';
930 value++;
931 child_set_env(env, envsize, cp, value);
933 fclose(f);
936 #ifdef HAVE_ETC_DEFAULT_LOGIN
938 * Return named variable from specified environment, or NULL if not present.
940 static char *
941 child_get_env(char **env, const char *name)
943 int i;
944 size_t len;
946 len = strlen(name);
947 for (i=0; env[i] != NULL; i++)
948 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
949 return(env[i] + len + 1);
950 return NULL;
954 * Read /etc/default/login.
955 * We pick up the PATH (or SUPATH for root) and UMASK.
957 static void
958 read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
960 char **tmpenv = NULL, *var;
961 u_int i, tmpenvsize = 0;
962 u_long mask;
965 * We don't want to copy the whole file to the child's environment,
966 * so we use a temporary environment and copy the variables we're
967 * interested in.
969 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
971 if (tmpenv == NULL)
972 return;
974 if (uid == 0)
975 var = child_get_env(tmpenv, "SUPATH");
976 else
977 var = child_get_env(tmpenv, "PATH");
978 if (var != NULL)
979 child_set_env(env, envsize, "PATH", var);
981 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
982 if (sscanf(var, "%5lo", &mask) == 1)
983 umask((mode_t)mask);
985 for (i = 0; tmpenv[i] != NULL; i++)
986 xfree(tmpenv[i]);
987 xfree(tmpenv);
989 #endif /* HAVE_ETC_DEFAULT_LOGIN */
991 void
992 copy_environment(char **source, char ***env, u_int *envsize)
994 char *var_name, *var_val;
995 int i;
997 if (source == NULL)
998 return;
1000 for(i = 0; source[i] != NULL; i++) {
1001 var_name = xstrdup(source[i]);
1002 if ((var_val = strstr(var_name, "=")) == NULL) {
1003 xfree(var_name);
1004 continue;
1006 *var_val++ = '\0';
1008 debug3("Copy environment: %s=%s", var_name, var_val);
1009 child_set_env(env, envsize, var_name, var_val);
1011 xfree(var_name);
1015 static char **
1016 do_setup_env(Session *s, const char *shell)
1018 char buf[256];
1019 u_int i, envsize;
1020 char **env, *laddr;
1021 struct passwd *pw = s->pw;
1022 #ifndef HAVE_LOGIN_CAP
1023 char *path = NULL;
1024 #endif
1026 /* Initialize the environment. */
1027 envsize = 100;
1028 env = xcalloc(envsize, sizeof(char *));
1029 env[0] = NULL;
1031 #ifdef HAVE_CYGWIN
1033 * The Windows environment contains some setting which are
1034 * important for a running system. They must not be dropped.
1037 char **p;
1039 p = fetch_windows_environment();
1040 copy_environment(p, &env, &envsize);
1041 free_windows_environment(p);
1043 #endif
1045 #ifdef GSSAPI
1046 /* Allow any GSSAPI methods that we've used to alter
1047 * the childs environment as they see fit
1049 ssh_gssapi_do_child(&env, &envsize);
1050 #endif
1052 if (!options.use_login) {
1053 /* Set basic environment. */
1054 for (i = 0; i < s->num_env; i++)
1055 child_set_env(&env, &envsize, s->env[i].name,
1056 s->env[i].val);
1058 child_set_env(&env, &envsize, "USER", pw->pw_name);
1059 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1060 #ifdef _AIX
1061 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
1062 #endif
1063 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1064 #ifdef HAVE_LOGIN_CAP
1065 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
1066 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1067 else
1068 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1069 #else /* HAVE_LOGIN_CAP */
1070 # ifndef HAVE_CYGWIN
1072 * There's no standard path on Windows. The path contains
1073 * important components pointing to the system directories,
1074 * needed for loading shared libraries. So the path better
1075 * remains intact here.
1077 # ifdef HAVE_ETC_DEFAULT_LOGIN
1078 read_etc_default_login(&env, &envsize, pw->pw_uid);
1079 path = child_get_env(env, "PATH");
1080 # endif /* HAVE_ETC_DEFAULT_LOGIN */
1081 if (path == NULL || *path == '\0') {
1082 child_set_env(&env, &envsize, "PATH",
1083 s->pw->pw_uid == 0 ?
1084 SUPERUSER_PATH : _PATH_STDPATH);
1086 # endif /* HAVE_CYGWIN */
1087 #endif /* HAVE_LOGIN_CAP */
1089 snprintf(buf, sizeof buf, "%.200s/%.50s",
1090 _PATH_MAILDIR, pw->pw_name);
1091 child_set_env(&env, &envsize, "MAIL", buf);
1093 /* Normal systems set SHELL by default. */
1094 child_set_env(&env, &envsize, "SHELL", shell);
1096 if (getenv("TZ"))
1097 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1099 /* Set custom environment options from RSA authentication. */
1100 if (!options.use_login) {
1101 while (custom_environment) {
1102 struct envstring *ce = custom_environment;
1103 char *str = ce->s;
1105 for (i = 0; str[i] != '=' && str[i]; i++)
1107 if (str[i] == '=') {
1108 str[i] = 0;
1109 child_set_env(&env, &envsize, str, str + i + 1);
1111 custom_environment = ce->next;
1112 xfree(ce->s);
1113 xfree(ce);
1117 /* SSH_CLIENT deprecated */
1118 snprintf(buf, sizeof buf, "%.50s %d %d",
1119 get_remote_ipaddr(), get_remote_port(), get_local_port());
1120 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1122 laddr = get_local_ipaddr(packet_get_connection_in());
1123 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1124 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1125 xfree(laddr);
1126 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1128 if (s->ttyfd != -1)
1129 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1130 if (s->term)
1131 child_set_env(&env, &envsize, "TERM", s->term);
1132 if (s->display)
1133 child_set_env(&env, &envsize, "DISPLAY", s->display);
1134 if (original_command)
1135 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1136 original_command);
1138 #ifdef _UNICOS
1139 if (cray_tmpdir[0] != '\0')
1140 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1141 #endif /* _UNICOS */
1144 * Since we clear KRB5CCNAME at startup, if it's set now then it
1145 * must have been set by a native authentication method (eg AIX or
1146 * SIA), so copy it to the child.
1149 char *cp;
1151 if ((cp = getenv("KRB5CCNAME")) != NULL)
1152 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1155 #ifdef _AIX
1157 char *cp;
1159 if ((cp = getenv("AUTHSTATE")) != NULL)
1160 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1161 read_environment_file(&env, &envsize, "/etc/environment");
1163 #endif
1164 #ifdef KRB5
1165 if (s->authctxt->krb5_ccname)
1166 child_set_env(&env, &envsize, "KRB5CCNAME",
1167 s->authctxt->krb5_ccname);
1168 #endif
1169 #ifdef USE_PAM
1171 * Pull in any environment variables that may have
1172 * been set by PAM.
1174 if (options.use_pam) {
1175 char **p;
1177 p = fetch_pam_child_environment();
1178 copy_environment(p, &env, &envsize);
1179 free_pam_environment(p);
1181 p = fetch_pam_environment();
1182 copy_environment(p, &env, &envsize);
1183 free_pam_environment(p);
1185 #endif /* USE_PAM */
1187 if (auth_sock_name != NULL)
1188 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1189 auth_sock_name);
1191 /* read $HOME/.ssh/environment. */
1192 if (options.permit_user_env && !options.use_login) {
1193 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1194 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
1195 read_environment_file(&env, &envsize, buf);
1197 if (debug_flag) {
1198 /* dump the environment */
1199 fprintf(stderr, "Environment:\n");
1200 for (i = 0; env[i]; i++)
1201 fprintf(stderr, " %.200s\n", env[i]);
1203 return env;
1207 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1208 * first in this order).
1210 static void
1211 do_rc_files(Session *s, const char *shell)
1213 FILE *f = NULL;
1214 char cmd[1024];
1215 int do_xauth;
1216 struct stat st;
1218 do_xauth =
1219 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1221 /* ignore _PATH_SSH_USER_RC for subsystems */
1222 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1223 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1224 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1225 if (debug_flag)
1226 fprintf(stderr, "Running %s\n", cmd);
1227 f = popen(cmd, "w");
1228 if (f) {
1229 if (do_xauth)
1230 fprintf(f, "%s %s\n", s->auth_proto,
1231 s->auth_data);
1232 pclose(f);
1233 } else
1234 fprintf(stderr, "Could not run %s\n",
1235 _PATH_SSH_USER_RC);
1236 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1237 if (debug_flag)
1238 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1239 _PATH_SSH_SYSTEM_RC);
1240 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1241 if (f) {
1242 if (do_xauth)
1243 fprintf(f, "%s %s\n", s->auth_proto,
1244 s->auth_data);
1245 pclose(f);
1246 } else
1247 fprintf(stderr, "Could not run %s\n",
1248 _PATH_SSH_SYSTEM_RC);
1249 } else if (do_xauth && options.xauth_location != NULL) {
1250 /* Add authority data to .Xauthority if appropriate. */
1251 if (debug_flag) {
1252 fprintf(stderr,
1253 "Running %.500s remove %.100s\n",
1254 options.xauth_location, s->auth_display);
1255 fprintf(stderr,
1256 "%.500s add %.100s %.100s %.100s\n",
1257 options.xauth_location, s->auth_display,
1258 s->auth_proto, s->auth_data);
1260 snprintf(cmd, sizeof cmd, "%s -q -",
1261 options.xauth_location);
1262 f = popen(cmd, "w");
1263 if (f) {
1264 fprintf(f, "remove %s\n",
1265 s->auth_display);
1266 fprintf(f, "add %s %s %s\n",
1267 s->auth_display, s->auth_proto,
1268 s->auth_data);
1269 pclose(f);
1270 } else {
1271 fprintf(stderr, "Could not run %s\n",
1272 cmd);
1277 static void
1278 do_nologin(struct passwd *pw)
1280 FILE *f = NULL;
1281 char buf[1024];
1283 #ifdef HAVE_LOGIN_CAP
1284 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1285 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1286 _PATH_NOLOGIN), "r");
1287 #else
1288 if (pw->pw_uid)
1289 f = fopen(_PATH_NOLOGIN, "r");
1290 #endif
1291 if (f) {
1292 /* /etc/nologin exists. Print its contents and exit. */
1293 logit("User %.100s not allowed because %s exists",
1294 pw->pw_name, _PATH_NOLOGIN);
1295 while (fgets(buf, sizeof(buf), f))
1296 fputs(buf, stderr);
1297 fclose(f);
1298 fflush(NULL);
1299 exit(254);
1304 * Chroot into a directory after checking it for safety: all path components
1305 * must be root-owned directories with strict permissions.
1307 static void
1308 safely_chroot(const char *path, uid_t uid)
1310 const char *cp;
1311 char component[MAXPATHLEN];
1312 struct stat st;
1314 if (*path != '/')
1315 fatal("chroot path does not begin at root");
1316 if (strlen(path) >= sizeof(component))
1317 fatal("chroot path too long");
1320 * Descend the path, checking that each component is a
1321 * root-owned directory with strict permissions.
1323 for (cp = path; cp != NULL;) {
1324 if ((cp = strchr(cp, '/')) == NULL)
1325 strlcpy(component, path, sizeof(component));
1326 else {
1327 cp++;
1328 memcpy(component, path, cp - path);
1329 component[cp - path] = '\0';
1332 debug3("%s: checking '%s'", __func__, component);
1334 if (stat(component, &st) != 0)
1335 fatal("%s: stat(\"%s\"): %s", __func__,
1336 component, strerror(errno));
1337 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1338 fatal("bad ownership or modes for chroot "
1339 "directory %s\"%s\"",
1340 cp == NULL ? "" : "component ", component);
1341 if (!S_ISDIR(st.st_mode))
1342 fatal("chroot path %s\"%s\" is not a directory",
1343 cp == NULL ? "" : "component ", component);
1347 if (chdir(path) == -1)
1348 fatal("Unable to chdir to chroot path \"%s\": "
1349 "%s", path, strerror(errno));
1350 if (chroot(path) == -1)
1351 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1352 if (chdir("/") == -1)
1353 fatal("%s: chdir(/) after chroot: %s",
1354 __func__, strerror(errno));
1355 verbose("Changed root directory to \"%s\"", path);
1358 /* Set login name, uid, gid, and groups. */
1359 void
1360 do_setusercontext(struct passwd *pw)
1362 char *chroot_path, *tmp;
1364 #ifndef HAVE_CYGWIN
1365 if (getuid() == 0 || geteuid() == 0)
1366 #endif /* HAVE_CYGWIN */
1369 #ifdef HAVE_SETPCRED
1370 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1371 fatal("Failed to set process credentials");
1372 #endif /* HAVE_SETPCRED */
1373 #ifdef HAVE_LOGIN_CAP
1374 # ifdef __bsdi__
1375 setpgid(0, 0);
1376 # endif
1377 #ifdef GSSAPI
1378 if (options.gss_authentication) {
1379 temporarily_use_uid(pw);
1380 ssh_gssapi_storecreds();
1381 restore_uid();
1383 #endif
1384 # ifdef USE_PAM
1385 if (options.use_pam) {
1386 do_pam_session();
1387 do_pam_setcred(use_privsep);
1389 # endif /* USE_PAM */
1390 if (setusercontext(lc, pw, pw->pw_uid,
1391 (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1392 perror("unable to set user context");
1393 exit(1);
1395 #else
1396 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1397 /* Sets login uid for accounting */
1398 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1399 error("setluid: %s", strerror(errno));
1400 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1402 if (setlogin(pw->pw_name) < 0)
1403 error("setlogin failed: %s", strerror(errno));
1404 if (setgid(pw->pw_gid) < 0) {
1405 perror("setgid");
1406 exit(1);
1408 /* Initialize the group list. */
1409 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1410 perror("initgroups");
1411 exit(1);
1413 endgrent();
1414 # ifdef GSSAPI
1415 if (options.gss_authentication) {
1416 temporarily_use_uid(pw);
1417 ssh_gssapi_storecreds();
1418 restore_uid();
1420 # endif
1421 # ifdef USE_PAM
1423 * PAM credentials may take the form of supplementary groups.
1424 * These will have been wiped by the above initgroups() call.
1425 * Reestablish them here.
1427 if (options.use_pam) {
1428 do_pam_session();
1429 do_pam_setcred(use_privsep);
1431 # endif /* USE_PAM */
1432 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1433 irix_setusercontext(pw);
1434 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
1435 # ifdef _AIX
1436 aix_usrinfo(pw);
1437 # endif /* _AIX */
1438 # ifdef USE_LIBIAF
1439 if (set_id(pw->pw_name) != 0) {
1440 exit(1);
1442 # endif /* USE_LIBIAF */
1443 #endif
1445 if (options.chroot_directory != NULL &&
1446 strcasecmp(options.chroot_directory, "none") != 0) {
1447 tmp = tilde_expand_filename(options.chroot_directory,
1448 pw->pw_uid);
1449 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1450 "u", pw->pw_name, (char *)NULL);
1451 safely_chroot(chroot_path, pw->pw_uid);
1452 free(tmp);
1453 free(chroot_path);
1456 #ifdef HAVE_LOGIN_CAP
1457 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1458 perror("unable to set user context (setuser)");
1459 exit(1);
1461 #else
1462 /* Permanently switch to the desired uid. */
1463 permanently_set_uid(pw);
1464 #endif
1467 #ifdef HAVE_CYGWIN
1468 if (is_winnt)
1469 #endif
1470 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1471 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1473 #ifdef WITH_SELINUX
1474 ssh_selinux_setup_exec_context(pw->pw_name);
1475 #endif
1478 static void
1479 do_pwchange(Session *s)
1481 fflush(NULL);
1482 fprintf(stderr, "WARNING: Your password has expired.\n");
1483 if (s->ttyfd != -1) {
1484 fprintf(stderr,
1485 "You must change your password now and login again!\n");
1486 #ifdef PASSWD_NEEDS_USERNAME
1487 execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
1488 (char *)NULL);
1489 #else
1490 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1491 #endif
1492 perror("passwd");
1493 } else {
1494 fprintf(stderr,
1495 "Password change required but no TTY available.\n");
1497 exit(1);
1500 static void
1501 launch_login(struct passwd *pw, const char *hostname)
1503 /* Launch login(1). */
1505 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1506 #ifdef xxxLOGIN_NEEDS_TERM
1507 (s->term ? s->term : "unknown"),
1508 #endif /* LOGIN_NEEDS_TERM */
1509 #ifdef LOGIN_NO_ENDOPT
1510 "-p", "-f", pw->pw_name, (char *)NULL);
1511 #else
1512 "-p", "-f", "--", pw->pw_name, (char *)NULL);
1513 #endif
1515 /* Login couldn't be executed, die. */
1517 perror("login");
1518 exit(1);
1521 static void
1522 child_close_fds(void)
1524 int i;
1526 if (packet_get_connection_in() == packet_get_connection_out())
1527 close(packet_get_connection_in());
1528 else {
1529 close(packet_get_connection_in());
1530 close(packet_get_connection_out());
1533 * Close all descriptors related to channels. They will still remain
1534 * open in the parent.
1536 /* XXX better use close-on-exec? -markus */
1537 channel_close_all();
1540 * Close any extra file descriptors. Note that there may still be
1541 * descriptors left by system functions. They will be closed later.
1543 endpwent();
1546 * Close any extra open file descriptors so that we don't have them
1547 * hanging around in clients. Note that we want to do this after
1548 * initgroups, because at least on Solaris 2.3 it leaves file
1549 * descriptors open.
1551 for (i = 3; i < 64; i++)
1552 close(i);
1556 * Performs common processing for the child, such as setting up the
1557 * environment, closing extra file descriptors, setting the user and group
1558 * ids, and executing the command or shell.
1560 #define ARGV_MAX 10
1561 void
1562 do_child(Session *s, const char *command)
1564 extern char **environ;
1565 char **env;
1566 char *argv[ARGV_MAX];
1567 const char *shell, *shell0, *hostname = NULL;
1568 struct passwd *pw = s->pw;
1570 /* remove hostkey from the child's memory */
1571 destroy_sensitive_data();
1573 /* Force a password change */
1574 if (s->authctxt->force_pwchange) {
1575 do_setusercontext(pw);
1576 child_close_fds();
1577 do_pwchange(s);
1578 exit(1);
1581 /* login(1) is only called if we execute the login shell */
1582 if (options.use_login && command != NULL)
1583 options.use_login = 0;
1585 #ifdef _UNICOS
1586 cray_setup(pw->pw_uid, pw->pw_name, command);
1587 #endif /* _UNICOS */
1590 * Login(1) does this as well, and it needs uid 0 for the "-h"
1591 * switch, so we let login(1) to this for us.
1593 if (!options.use_login) {
1594 #ifdef HAVE_OSF_SIA
1595 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
1596 if (!check_quietlogin(s, command))
1597 do_motd();
1598 #else /* HAVE_OSF_SIA */
1599 /* When PAM is enabled we rely on it to do the nologin check */
1600 if (!options.use_pam)
1601 do_nologin(pw);
1602 do_setusercontext(pw);
1604 * PAM session modules in do_setusercontext may have
1605 * generated messages, so if this in an interactive
1606 * login then display them too.
1608 if (!check_quietlogin(s, command))
1609 display_loginmsg();
1610 #endif /* HAVE_OSF_SIA */
1613 #ifdef USE_PAM
1614 if (options.use_pam && !options.use_login && !is_pam_session_open()) {
1615 debug3("PAM session not opened, exiting");
1616 display_loginmsg();
1617 exit(254);
1619 #endif
1622 * Get the shell from the password data. An empty shell field is
1623 * legal, and means /bin/sh.
1625 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1628 * Make sure $SHELL points to the shell from the password file,
1629 * even if shell is overridden from login.conf
1631 env = do_setup_env(s, shell);
1633 #ifdef HAVE_LOGIN_CAP
1634 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1635 #endif
1637 /* we have to stash the hostname before we close our socket. */
1638 if (options.use_login)
1639 hostname = get_remote_name_or_ip(utmp_len,
1640 options.use_dns);
1642 * Close the connection descriptors; note that this is the child, and
1643 * the server will still have the socket open, and it is important
1644 * that we do not shutdown it. Note that the descriptors cannot be
1645 * closed before building the environment, as we call
1646 * get_remote_ipaddr there.
1648 child_close_fds();
1651 * Must take new environment into use so that .ssh/rc,
1652 * /etc/ssh/sshrc and xauth are run in the proper environment.
1654 environ = env;
1656 #if defined(KRB5) && defined(USE_AFS)
1658 * At this point, we check to see if AFS is active and if we have
1659 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1660 * if we can (and need to) extend the ticket into an AFS token. If
1661 * we don't do this, we run into potential problems if the user's
1662 * home directory is in AFS and it's not world-readable.
1665 if (options.kerberos_get_afs_token && k_hasafs() &&
1666 (s->authctxt->krb5_ctx != NULL)) {
1667 char cell[64];
1669 debug("Getting AFS token");
1671 k_setpag();
1673 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1674 krb5_afslog(s->authctxt->krb5_ctx,
1675 s->authctxt->krb5_fwd_ccache, cell, NULL);
1677 krb5_afslog_home(s->authctxt->krb5_ctx,
1678 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1680 #endif
1682 /* Change current directory to the user's home directory. */
1683 if (chdir(pw->pw_dir) < 0) {
1684 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1685 pw->pw_dir, strerror(errno));
1686 #ifdef HAVE_LOGIN_CAP
1687 if (login_getcapbool(lc, "requirehome", 0))
1688 exit(1);
1689 #endif
1692 if (!options.use_login)
1693 do_rc_files(s, shell);
1695 /* restore SIGPIPE for child */
1696 signal(SIGPIPE, SIG_DFL);
1698 if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1699 extern int optind, optreset;
1700 int i;
1701 char *p, *args;
1703 setproctitle("%s@internal-sftp-server", s->pw->pw_name);
1704 args = strdup(command ? command : "sftp-server");
1705 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1706 if (i < ARGV_MAX - 1)
1707 argv[i++] = p;
1708 argv[i] = NULL;
1709 optind = optreset = 1;
1710 __progname = argv[0];
1711 exit(sftp_server_main(i, argv, s->pw));
1714 if (options.use_login) {
1715 launch_login(pw, hostname);
1716 /* NEVERREACHED */
1719 /* Get the last component of the shell name. */
1720 if ((shell0 = strrchr(shell, '/')) != NULL)
1721 shell0++;
1722 else
1723 shell0 = shell;
1726 * If we have no command, execute the shell. In this case, the shell
1727 * name to be passed in argv[0] is preceded by '-' to indicate that
1728 * this is a login shell.
1730 if (!command) {
1731 char argv0[256];
1733 /* Start the shell. Set initial character to '-'. */
1734 argv0[0] = '-';
1736 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1737 >= sizeof(argv0) - 1) {
1738 errno = EINVAL;
1739 perror(shell);
1740 exit(1);
1743 /* Execute the shell. */
1744 argv[0] = argv0;
1745 argv[1] = NULL;
1746 execve(shell, argv, env);
1748 /* Executing the shell failed. */
1749 perror(shell);
1750 exit(1);
1753 * Execute the command using the user's shell. This uses the -c
1754 * option to execute the command.
1756 argv[0] = (char *) shell0;
1757 argv[1] = "-c";
1758 argv[2] = (char *) command;
1759 argv[3] = NULL;
1760 execve(shell, argv, env);
1761 perror(shell);
1762 exit(1);
1765 Session *
1766 session_new(void)
1768 int i;
1769 static int did_init = 0;
1770 if (!did_init) {
1771 debug("session_new: init");
1772 for (i = 0; i < MAX_SESSIONS; i++) {
1773 sessions[i].used = 0;
1775 did_init = 1;
1777 for (i = 0; i < MAX_SESSIONS; i++) {
1778 Session *s = &sessions[i];
1779 if (! s->used) {
1780 memset(s, 0, sizeof(*s));
1781 s->chanid = -1;
1782 s->ptyfd = -1;
1783 s->ttyfd = -1;
1784 s->used = 1;
1785 s->self = i;
1786 s->x11_chanids = NULL;
1787 debug("session_new: session %d", i);
1788 return s;
1791 return NULL;
1794 static void
1795 session_dump(void)
1797 int i;
1798 for (i = 0; i < MAX_SESSIONS; i++) {
1799 Session *s = &sessions[i];
1800 debug("dump: used %d session %d %p channel %d pid %ld",
1801 s->used,
1802 s->self,
1804 s->chanid,
1805 (long)s->pid);
1810 session_open(Authctxt *authctxt, int chanid)
1812 Session *s = session_new();
1813 debug("session_open: channel %d", chanid);
1814 if (s == NULL) {
1815 error("no more sessions");
1816 return 0;
1818 s->authctxt = authctxt;
1819 s->pw = authctxt->pw;
1820 if (s->pw == NULL || !authctxt->valid)
1821 fatal("no user for session %d", s->self);
1822 debug("session_open: session %d: link with channel %d", s->self, chanid);
1823 s->chanid = chanid;
1824 return 1;
1827 Session *
1828 session_by_tty(char *tty)
1830 int i;
1831 for (i = 0; i < MAX_SESSIONS; i++) {
1832 Session *s = &sessions[i];
1833 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1834 debug("session_by_tty: session %d tty %s", i, tty);
1835 return s;
1838 debug("session_by_tty: unknown tty %.100s", tty);
1839 session_dump();
1840 return NULL;
1843 static Session *
1844 session_by_channel(int id)
1846 int i;
1847 for (i = 0; i < MAX_SESSIONS; i++) {
1848 Session *s = &sessions[i];
1849 if (s->used && s->chanid == id) {
1850 debug("session_by_channel: session %d channel %d", i, id);
1851 return s;
1854 debug("session_by_channel: unknown channel %d", id);
1855 session_dump();
1856 return NULL;
1859 static Session *
1860 session_by_x11_channel(int id)
1862 int i, j;
1864 for (i = 0; i < MAX_SESSIONS; i++) {
1865 Session *s = &sessions[i];
1867 if (s->x11_chanids == NULL || !s->used)
1868 continue;
1869 for (j = 0; s->x11_chanids[j] != -1; j++) {
1870 if (s->x11_chanids[j] == id) {
1871 debug("session_by_x11_channel: session %d "
1872 "channel %d", s->self, id);
1873 return s;
1877 debug("session_by_x11_channel: unknown channel %d", id);
1878 session_dump();
1879 return NULL;
1882 static Session *
1883 session_by_pid(pid_t pid)
1885 int i;
1886 debug("session_by_pid: pid %ld", (long)pid);
1887 for (i = 0; i < MAX_SESSIONS; i++) {
1888 Session *s = &sessions[i];
1889 if (s->used && s->pid == pid)
1890 return s;
1892 error("session_by_pid: unknown pid %ld", (long)pid);
1893 session_dump();
1894 return NULL;
1897 static int
1898 session_window_change_req(Session *s)
1900 s->col = packet_get_int();
1901 s->row = packet_get_int();
1902 s->xpixel = packet_get_int();
1903 s->ypixel = packet_get_int();
1904 packet_check_eom();
1905 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1906 return 1;
1909 static int
1910 session_pty_req(Session *s)
1912 u_int len;
1913 int n_bytes;
1915 if (no_pty_flag) {
1916 debug("Allocating a pty not permitted for this authentication.");
1917 return 0;
1919 if (s->ttyfd != -1) {
1920 packet_disconnect("Protocol error: you already have a pty.");
1921 return 0;
1924 s->term = packet_get_string(&len);
1926 if (compat20) {
1927 s->col = packet_get_int();
1928 s->row = packet_get_int();
1929 } else {
1930 s->row = packet_get_int();
1931 s->col = packet_get_int();
1933 s->xpixel = packet_get_int();
1934 s->ypixel = packet_get_int();
1936 if (strcmp(s->term, "") == 0) {
1937 xfree(s->term);
1938 s->term = NULL;
1941 /* Allocate a pty and open it. */
1942 debug("Allocating pty.");
1943 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1944 if (s->term)
1945 xfree(s->term);
1946 s->term = NULL;
1947 s->ptyfd = -1;
1948 s->ttyfd = -1;
1949 error("session_pty_req: session %d alloc failed", s->self);
1950 return 0;
1952 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1954 /* for SSH1 the tty modes length is not given */
1955 if (!compat20)
1956 n_bytes = packet_remaining();
1957 tty_parse_modes(s->ttyfd, &n_bytes);
1959 if (!use_privsep)
1960 pty_setowner(s->pw, s->tty);
1962 /* Set window size from the packet. */
1963 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1965 packet_check_eom();
1966 session_proctitle(s);
1967 return 1;
1970 static int
1971 session_subsystem_req(Session *s)
1973 struct stat st;
1974 u_int len;
1975 int success = 0;
1976 char *prog, *cmd, *subsys = packet_get_string(&len);
1977 u_int i;
1979 packet_check_eom();
1980 logit("subsystem request for %.100s", subsys);
1982 for (i = 0; i < options.num_subsystems; i++) {
1983 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1984 prog = options.subsystem_command[i];
1985 cmd = options.subsystem_args[i];
1986 if (!strcmp(INTERNAL_SFTP_NAME, prog)) {
1987 s->is_subsystem = SUBSYSTEM_INT_SFTP;
1988 } else if (stat(prog, &st) < 0) {
1989 error("subsystem: cannot stat %s: %s", prog,
1990 strerror(errno));
1991 break;
1992 } else {
1993 s->is_subsystem = SUBSYSTEM_EXT;
1995 debug("subsystem: exec() %s", cmd);
1996 do_exec(s, cmd);
1997 success = 1;
1998 break;
2002 if (!success)
2003 logit("subsystem request for %.100s failed, subsystem not found",
2004 subsys);
2006 xfree(subsys);
2007 return success;
2010 static int
2011 session_x11_req(Session *s)
2013 int success;
2015 if (s->auth_proto != NULL || s->auth_data != NULL) {
2016 error("session_x11_req: session %d: "
2017 "x11 forwarding already active", s->self);
2018 return 0;
2020 s->single_connection = packet_get_char();
2021 s->auth_proto = packet_get_string(NULL);
2022 s->auth_data = packet_get_string(NULL);
2023 s->screen = packet_get_int();
2024 packet_check_eom();
2026 success = session_setup_x11fwd(s);
2027 if (!success) {
2028 xfree(s->auth_proto);
2029 xfree(s->auth_data);
2030 s->auth_proto = NULL;
2031 s->auth_data = NULL;
2033 return success;
2036 static int
2037 session_shell_req(Session *s)
2039 packet_check_eom();
2040 do_exec(s, NULL);
2041 return 1;
2044 static int
2045 session_exec_req(Session *s)
2047 u_int len;
2048 char *command = packet_get_string(&len);
2049 packet_check_eom();
2050 do_exec(s, command);
2051 xfree(command);
2052 return 1;
2055 static int
2056 session_break_req(Session *s)
2059 packet_get_int(); /* ignored */
2060 packet_check_eom();
2062 if (s->ttyfd == -1 ||
2063 tcsendbreak(s->ttyfd, 0) < 0)
2064 return 0;
2065 return 1;
2068 static int
2069 session_env_req(Session *s)
2071 char *name, *val;
2072 u_int name_len, val_len, i;
2074 name = packet_get_string(&name_len);
2075 val = packet_get_string(&val_len);
2076 packet_check_eom();
2078 /* Don't set too many environment variables */
2079 if (s->num_env > 128) {
2080 debug2("Ignoring env request %s: too many env vars", name);
2081 goto fail;
2084 for (i = 0; i < options.num_accept_env; i++) {
2085 if (match_pattern(name, options.accept_env[i])) {
2086 debug2("Setting env %d: %s=%s", s->num_env, name, val);
2087 s->env = xrealloc(s->env, s->num_env + 1,
2088 sizeof(*s->env));
2089 s->env[s->num_env].name = name;
2090 s->env[s->num_env].val = val;
2091 s->num_env++;
2092 return (1);
2095 debug2("Ignoring env request %s: disallowed name", name);
2097 fail:
2098 xfree(name);
2099 xfree(val);
2100 return (0);
2103 static int
2104 session_auth_agent_req(Session *s)
2106 static int called = 0;
2107 packet_check_eom();
2108 if (no_agent_forwarding_flag) {
2109 debug("session_auth_agent_req: no_agent_forwarding_flag");
2110 return 0;
2112 if (called) {
2113 return 0;
2114 } else {
2115 called = 1;
2116 return auth_input_request_forwarding(s->pw);
2121 session_input_channel_req(Channel *c, const char *rtype)
2123 int success = 0;
2124 Session *s;
2126 if ((s = session_by_channel(c->self)) == NULL) {
2127 logit("session_input_channel_req: no session %d req %.100s",
2128 c->self, rtype);
2129 return 0;
2131 debug("session_input_channel_req: session %d req %s", s->self, rtype);
2134 * a session is in LARVAL state until a shell, a command
2135 * or a subsystem is executed
2137 if (c->type == SSH_CHANNEL_LARVAL) {
2138 if (strcmp(rtype, "shell") == 0) {
2139 success = session_shell_req(s);
2140 } else if (strcmp(rtype, "exec") == 0) {
2141 success = session_exec_req(s);
2142 } else if (strcmp(rtype, "pty-req") == 0) {
2143 success = session_pty_req(s);
2144 } else if (strcmp(rtype, "x11-req") == 0) {
2145 success = session_x11_req(s);
2146 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
2147 success = session_auth_agent_req(s);
2148 } else if (strcmp(rtype, "subsystem") == 0) {
2149 success = session_subsystem_req(s);
2150 } else if (strcmp(rtype, "env") == 0) {
2151 success = session_env_req(s);
2154 if (strcmp(rtype, "window-change") == 0) {
2155 success = session_window_change_req(s);
2156 } else if (strcmp(rtype, "break") == 0) {
2157 success = session_break_req(s);
2160 return success;
2163 void
2164 session_set_fds(Session *s, int fdin, int fdout, int fderr)
2166 if (!compat20)
2167 fatal("session_set_fds: called for proto != 2.0");
2169 * now that have a child and a pipe to the child,
2170 * we can activate our channel and register the fd's
2172 if (s->chanid == -1)
2173 fatal("no channel for session %d", s->self);
2174 channel_set_fds(s->chanid,
2175 fdout, fdin, fderr,
2176 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2178 CHAN_SES_WINDOW_DEFAULT);
2182 * Function to perform pty cleanup. Also called if we get aborted abnormally
2183 * (e.g., due to a dropped connection).
2185 void
2186 session_pty_cleanup2(Session *s)
2188 if (s == NULL) {
2189 error("session_pty_cleanup: no session");
2190 return;
2192 if (s->ttyfd == -1)
2193 return;
2195 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
2197 /* Record that the user has logged out. */
2198 if (s->pid != 0)
2199 record_logout(s->pid, s->tty, s->pw->pw_name);
2201 /* Release the pseudo-tty. */
2202 if (getuid() == 0)
2203 pty_release(s->tty);
2206 * Close the server side of the socket pairs. We must do this after
2207 * the pty cleanup, so that another process doesn't get this pty
2208 * while we're still cleaning up.
2210 if (close(s->ptymaster) < 0)
2211 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
2213 /* unlink pty from session */
2214 s->ttyfd = -1;
2217 void
2218 session_pty_cleanup(Session *s)
2220 PRIVSEP(session_pty_cleanup2(s));
2223 static char *
2224 sig2name(int sig)
2226 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2227 SSH_SIG(ABRT);
2228 SSH_SIG(ALRM);
2229 SSH_SIG(FPE);
2230 SSH_SIG(HUP);
2231 SSH_SIG(ILL);
2232 SSH_SIG(INT);
2233 SSH_SIG(KILL);
2234 SSH_SIG(PIPE);
2235 SSH_SIG(QUIT);
2236 SSH_SIG(SEGV);
2237 SSH_SIG(TERM);
2238 SSH_SIG(USR1);
2239 SSH_SIG(USR2);
2240 #undef SSH_SIG
2241 return "SIG@openssh.com";
2244 static void
2245 session_close_x11(int id)
2247 Channel *c;
2249 if ((c = channel_by_id(id)) == NULL) {
2250 debug("session_close_x11: x11 channel %d missing", id);
2251 } else {
2252 /* Detach X11 listener */
2253 debug("session_close_x11: detach x11 channel %d", id);
2254 channel_cancel_cleanup(id);
2255 if (c->ostate != CHAN_OUTPUT_CLOSED)
2256 chan_mark_dead(c);
2260 static void
2261 session_close_single_x11(int id, void *arg)
2263 Session *s;
2264 u_int i;
2266 debug3("session_close_single_x11: channel %d", id);
2267 channel_cancel_cleanup(id);
2268 if ((s = session_by_x11_channel(id)) == NULL)
2269 fatal("session_close_single_x11: no x11 channel %d", id);
2270 for (i = 0; s->x11_chanids[i] != -1; i++) {
2271 debug("session_close_single_x11: session %d: "
2272 "closing channel %d", s->self, s->x11_chanids[i]);
2274 * The channel "id" is already closing, but make sure we
2275 * close all of its siblings.
2277 if (s->x11_chanids[i] != id)
2278 session_close_x11(s->x11_chanids[i]);
2280 xfree(s->x11_chanids);
2281 s->x11_chanids = NULL;
2282 if (s->display) {
2283 xfree(s->display);
2284 s->display = NULL;
2286 if (s->auth_proto) {
2287 xfree(s->auth_proto);
2288 s->auth_proto = NULL;
2290 if (s->auth_data) {
2291 xfree(s->auth_data);
2292 s->auth_data = NULL;
2294 if (s->auth_display) {
2295 xfree(s->auth_display);
2296 s->auth_display = NULL;
2300 static void
2301 session_exit_message(Session *s, int status)
2303 Channel *c;
2305 if ((c = channel_lookup(s->chanid)) == NULL)
2306 fatal("session_exit_message: session %d: no channel %d",
2307 s->self, s->chanid);
2308 debug("session_exit_message: session %d channel %d pid %ld",
2309 s->self, s->chanid, (long)s->pid);
2311 if (WIFEXITED(status)) {
2312 channel_request_start(s->chanid, "exit-status", 0);
2313 packet_put_int(WEXITSTATUS(status));
2314 packet_send();
2315 } else if (WIFSIGNALED(status)) {
2316 channel_request_start(s->chanid, "exit-signal", 0);
2317 packet_put_cstring(sig2name(WTERMSIG(status)));
2318 #ifdef WCOREDUMP
2319 packet_put_char(WCOREDUMP(status));
2320 #else /* WCOREDUMP */
2321 packet_put_char(0);
2322 #endif /* WCOREDUMP */
2323 packet_put_cstring("");
2324 packet_put_cstring("");
2325 packet_send();
2326 } else {
2327 /* Some weird exit cause. Just exit. */
2328 packet_disconnect("wait returned status %04x.", status);
2331 /* disconnect channel */
2332 debug("session_exit_message: release channel %d", s->chanid);
2335 * Adjust cleanup callback attachment to send close messages when
2336 * the channel gets EOF. The session will be then be closed
2337 * by session_close_by_channel when the childs close their fds.
2339 channel_register_cleanup(c->self, session_close_by_channel, 1);
2342 * emulate a write failure with 'chan_write_failed', nobody will be
2343 * interested in data we write.
2344 * Note that we must not call 'chan_read_failed', since there could
2345 * be some more data waiting in the pipe.
2347 if (c->ostate != CHAN_OUTPUT_CLOSED)
2348 chan_write_failed(c);
2351 void
2352 session_close(Session *s)
2354 u_int i;
2356 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2357 if (s->ttyfd != -1)
2358 session_pty_cleanup(s);
2359 if (s->term)
2360 xfree(s->term);
2361 if (s->display)
2362 xfree(s->display);
2363 if (s->x11_chanids)
2364 xfree(s->x11_chanids);
2365 if (s->auth_display)
2366 xfree(s->auth_display);
2367 if (s->auth_data)
2368 xfree(s->auth_data);
2369 if (s->auth_proto)
2370 xfree(s->auth_proto);
2371 s->used = 0;
2372 if (s->env != NULL) {
2373 for (i = 0; i < s->num_env; i++) {
2374 xfree(s->env[i].name);
2375 xfree(s->env[i].val);
2377 xfree(s->env);
2379 session_proctitle(s);
2382 void
2383 session_close_by_pid(pid_t pid, int status)
2385 Session *s = session_by_pid(pid);
2386 if (s == NULL) {
2387 debug("session_close_by_pid: no session for pid %ld",
2388 (long)pid);
2389 return;
2391 if (s->chanid != -1)
2392 session_exit_message(s, status);
2393 if (s->ttyfd != -1)
2394 session_pty_cleanup(s);
2395 s->pid = 0;
2399 * this is called when a channel dies before
2400 * the session 'child' itself dies
2402 void
2403 session_close_by_channel(int id, void *arg)
2405 Session *s = session_by_channel(id);
2406 u_int i;
2408 if (s == NULL) {
2409 debug("session_close_by_channel: no session for id %d", id);
2410 return;
2412 debug("session_close_by_channel: channel %d child %ld",
2413 id, (long)s->pid);
2414 if (s->pid != 0) {
2415 debug("session_close_by_channel: channel %d: has child", id);
2417 * delay detach of session, but release pty, since
2418 * the fd's to the child are already closed
2420 if (s->ttyfd != -1)
2421 session_pty_cleanup(s);
2422 return;
2424 /* detach by removing callback */
2425 channel_cancel_cleanup(s->chanid);
2427 /* Close any X11 listeners associated with this session */
2428 if (s->x11_chanids != NULL) {
2429 for (i = 0; s->x11_chanids[i] != -1; i++) {
2430 session_close_x11(s->x11_chanids[i]);
2431 s->x11_chanids[i] = -1;
2435 s->chanid = -1;
2436 session_close(s);
2439 void
2440 session_destroy_all(void (*closefunc)(Session *))
2442 int i;
2443 for (i = 0; i < MAX_SESSIONS; i++) {
2444 Session *s = &sessions[i];
2445 if (s->used) {
2446 if (closefunc != NULL)
2447 closefunc(s);
2448 else
2449 session_close(s);
2454 static char *
2455 session_tty_list(void)
2457 static char buf[1024];
2458 int i;
2459 char *cp;
2461 buf[0] = '\0';
2462 for (i = 0; i < MAX_SESSIONS; i++) {
2463 Session *s = &sessions[i];
2464 if (s->used && s->ttyfd != -1) {
2466 if (strncmp(s->tty, "/dev/", 5) != 0) {
2467 cp = strrchr(s->tty, '/');
2468 cp = (cp == NULL) ? s->tty : cp + 1;
2469 } else
2470 cp = s->tty + 5;
2472 if (buf[0] != '\0')
2473 strlcat(buf, ",", sizeof buf);
2474 strlcat(buf, cp, sizeof buf);
2477 if (buf[0] == '\0')
2478 strlcpy(buf, "notty", sizeof buf);
2479 return buf;
2482 void
2483 session_proctitle(Session *s)
2485 if (s->pw == NULL)
2486 error("no user for session %d", s->self);
2487 else
2488 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2492 session_setup_x11fwd(Session *s)
2494 struct stat st;
2495 char display[512], auth_display[512];
2496 char hostname[MAXHOSTNAMELEN];
2497 u_int i;
2499 if (no_x11_forwarding_flag) {
2500 packet_send_debug("X11 forwarding disabled in user configuration file.");
2501 return 0;
2503 if (!options.x11_forwarding) {
2504 debug("X11 forwarding disabled in server configuration file.");
2505 return 0;
2507 if (!options.xauth_location ||
2508 (stat(options.xauth_location, &st) == -1)) {
2509 packet_send_debug("No xauth program; cannot forward with spoofing.");
2510 return 0;
2512 if (options.use_login) {
2513 packet_send_debug("X11 forwarding disabled; "
2514 "not compatible with UseLogin=yes.");
2515 return 0;
2517 if (s->display != NULL) {
2518 debug("X11 display already set.");
2519 return 0;
2521 if (x11_create_display_inet(options.x11_display_offset,
2522 options.x11_use_localhost, s->single_connection,
2523 &s->display_number, &s->x11_chanids) == -1) {
2524 debug("x11_create_display_inet failed.");
2525 return 0;
2527 for (i = 0; s->x11_chanids[i] != -1; i++) {
2528 channel_register_cleanup(s->x11_chanids[i],
2529 session_close_single_x11, 0);
2532 /* Set up a suitable value for the DISPLAY variable. */
2533 if (gethostname(hostname, sizeof(hostname)) < 0)
2534 fatal("gethostname: %.100s", strerror(errno));
2536 * auth_display must be used as the displayname when the
2537 * authorization entry is added with xauth(1). This will be
2538 * different than the DISPLAY string for localhost displays.
2540 if (options.x11_use_localhost) {
2541 snprintf(display, sizeof display, "localhost:%u.%u",
2542 s->display_number, s->screen);
2543 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2544 s->display_number, s->screen);
2545 s->display = xstrdup(display);
2546 s->auth_display = xstrdup(auth_display);
2547 } else {
2548 #ifdef IPADDR_IN_DISPLAY
2549 struct hostent *he;
2550 struct in_addr my_addr;
2552 he = gethostbyname(hostname);
2553 if (he == NULL) {
2554 error("Can't get IP address for X11 DISPLAY.");
2555 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2556 return 0;
2558 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2559 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
2560 s->display_number, s->screen);
2561 #else
2562 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2563 s->display_number, s->screen);
2564 #endif
2565 s->display = xstrdup(display);
2566 s->auth_display = xstrdup(display);
2569 return 1;
2572 static void
2573 do_authenticated2(Authctxt *authctxt)
2575 server_loop2(authctxt);
2578 void
2579 do_cleanup(Authctxt *authctxt)
2581 static int called = 0;
2583 debug("do_cleanup");
2585 /* no cleanup if we're in the child for login shell */
2586 if (is_child)
2587 return;
2589 /* avoid double cleanup */
2590 if (called)
2591 return;
2592 called = 1;
2594 if (authctxt == NULL)
2595 return;
2597 #ifdef USE_PAM
2598 if (options.use_pam) {
2599 sshpam_cleanup();
2600 sshpam_thread_cleanup();
2602 #endif
2604 if (!authctxt->authenticated)
2605 return;
2607 #ifdef KRB5
2608 if (options.kerberos_ticket_cleanup &&
2609 authctxt->krb5_ctx)
2610 krb5_cleanup_proc(authctxt);
2611 #endif
2613 #ifdef GSSAPI
2614 if (compat20 && options.gss_cleanup_creds)
2615 ssh_gssapi_cleanup_creds();
2616 #endif
2618 /* remove agent socket */
2619 auth_sock_cleanup_proc(authctxt->pw);
2622 * Cleanup ptys/utmp only if privsep is disabled,
2623 * or if running in monitor.
2625 if (!use_privsep || mm_is_monitor())
2626 session_destroy_all(session_pty_cleanup2);