2 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * SSH2 support by Markus Friedl.
7 * Copyright (c) 2000 Markus Friedl. All rights reserved.
11 RCSID("$OpenBSD: session.c,v 1.25 2000/08/17 20:06:34 markus Exp $");
29 #include "auth-options.h"
31 #ifdef WITH_IRIX_PROJECT
33 #endif /* WITH_IRIX_PROJECT */
35 #if defined(HAVE_USERSEC_H)
45 #if defined(HAVE_GETUSERATTR) && !defined(S_UFSIZE_HARD) && defined(S_UFSIZE)
46 # define S_UFSIZE_HARD S_UFSIZE "_hard"
47 # define S_UCPU_HARD S_UCPU "_hard"
48 # define S_UDATA_HARD S_UDATA "_hard"
49 # define S_USTACK_HARD S_USTACK "_hard"
50 # define S_URSS_HARD S_URSS "_hard"
51 # define S_UCORE_HARD S_UCORE "_hard"
52 # define S_UNOFILE_HARD S_UNOFILE "_hard"
58 typedef struct Session Session;
67 int ptyfd, ttyfd, ptymaster;
68 int row, col, xpixel, ypixel;
75 int single_connection;
82 Session *session_new(void);
83 void session_set_fds(Session *s, int fdin, int fdout, int fderr);
84 void session_pty_cleanup(Session *s);
85 void session_proctitle(Session *s);
86 void do_exec_pty(Session *s, const char *command, struct passwd * pw);
87 void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
88 void do_login(Session *s);
91 do_child(const char *command, struct passwd * pw, const char *term,
92 const char *display, const char *auth_proto,
93 const char *auth_data, const char *ttyname);
96 extern ServerOptions options;
97 #ifdef HAVE___PROGNAME
98 extern char *__progname;
99 #else /* HAVE___PROGNAME */
100 static const char *__progname = "sshd";
101 #endif /* HAVE___PROGNAME */
103 extern int log_stderr;
104 extern int debug_flag;
105 extern unsigned int utmp_len;
107 extern int startup_pipe;
109 /* Local Xauthority file. */
110 static char *xauthfile;
113 #define MAX_SESSIONS 10
114 Session sessions[MAX_SESSIONS];
115 #ifdef WITH_AIXAUTHENTICATE
116 /* AIX's lastlogin message, set in auth1.c */
118 #endif /* WITH_AIXAUTHENTICATE */
121 * Remove local Xauthority file.
124 xauthfile_cleanup_proc(void *ignore)
126 debug("xauthfile_cleanup_proc called");
128 if (xauthfile != NULL) {
131 p = strrchr(xauthfile, '/');
142 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
143 * dropped connection).
146 pty_cleanup_proc(void *session)
150 fatal("pty_cleanup_proc: no session");
151 debug("pty_cleanup_proc: %s", s->tty);
154 /* Record that the user has logged out. */
155 record_logout(s->pid, s->tty);
158 /* Release the pseudo-tty. */
163 * Prepares for an interactive session. This is called after the user has
164 * been successfully authenticated. During this message exchange, pseudo
165 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
166 * are requested, etc.
169 do_authenticated(struct passwd * pw)
173 int compression_level = 0, enable_compression_after_reply = 0;
178 unsigned int proto_len, data_len, dlen;
181 * Cancel the alarm we set to limit the time taken for
185 if (startup_pipe != -1) {
191 * Inform the channel mechanism that we are the server side and that
192 * the client may request to connect to any port at all. (The user
193 * could do it anyway, and we wouldn\'t know what is permitted except
194 * by the client telling us, so we can equally well trust the client
195 * not to request anything bogus.)
197 if (!no_port_forwarding_flag)
198 channel_permit_all_opens();
204 * We stay in this loop until the client requests to execute a shell
210 /* Get a packet from the client. */
211 type = packet_read(&plen);
213 /* Process the packet. */
215 case SSH_CMSG_REQUEST_COMPRESSION:
216 packet_integrity_check(plen, 4, type);
217 compression_level = packet_get_int();
218 if (compression_level < 1 || compression_level > 9) {
219 packet_send_debug("Received illegal compression level %d.",
223 /* Enable compression after we have responded with SUCCESS. */
224 enable_compression_after_reply = 1;
228 case SSH_CMSG_REQUEST_PTY:
230 debug("Allocating a pty not permitted for this authentication.");
234 packet_disconnect("Protocol error: you already have a pty.");
236 debug("Allocating pty.");
238 /* Allocate a pty and open it. */
239 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
241 error("Failed to allocate pty.");
244 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
245 pty_setowner(pw, s->tty);
247 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
248 s->term = packet_get_string(&dlen);
249 packet_integrity_check(dlen, strlen(s->term), type);
250 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
251 /* Remaining bytes */
252 n_bytes = plen - (4 + dlen + 4 * 4);
254 if (strcmp(s->term, "") == 0) {
258 /* Get window size from the packet. */
259 s->row = packet_get_int();
260 s->col = packet_get_int();
261 s->xpixel = packet_get_int();
262 s->ypixel = packet_get_int();
263 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
265 /* Get tty modes from the packet. */
266 tty_parse_modes(s->ttyfd, &n_bytes);
267 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
269 session_proctitle(s);
271 /* Indicate that we now have a pty. */
276 case SSH_CMSG_X11_REQUEST_FORWARDING:
277 if (!options.x11_forwarding) {
278 packet_send_debug("X11 forwarding disabled in server configuration file.");
281 if (!options.xauth_location) {
282 packet_send_debug("No xauth program; cannot forward with spoofing.");
285 if (no_x11_forwarding_flag) {
286 packet_send_debug("X11 forwarding not permitted for this authentication.");
289 debug("Received request for X11 forwarding with auth spoofing.");
290 if (s->display != NULL)
291 packet_disconnect("Protocol error: X11 display already set.");
293 s->auth_proto = packet_get_string(&proto_len);
294 s->auth_data = packet_get_string(&data_len);
295 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
297 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
298 s->screen = packet_get_int();
301 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
303 if (s->display == NULL)
306 /* Setup to always have a local .Xauthority. */
307 xauthfile = xmalloc(MAXPATHLEN);
308 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
309 temporarily_use_uid(pw->pw_uid);
310 if (mkdtemp(xauthfile) == NULL) {
312 error("private X11 dir: mkdtemp %s failed: %s",
313 xauthfile, strerror(errno));
316 /* XXXX remove listening channels */
319 strlcat(xauthfile, "/cookies", MAXPATHLEN);
320 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
322 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
326 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
327 if (no_agent_forwarding_flag || compat13) {
328 debug("Authentication agent forwarding not permitted for this authentication.");
331 debug("Received authentication agent forwarding request.");
332 success = auth_input_request_forwarding(pw);
335 case SSH_CMSG_PORT_FORWARD_REQUEST:
336 if (no_port_forwarding_flag) {
337 debug("Port forwarding not permitted for this authentication.");
340 debug("Received TCP/IP port forwarding request.");
341 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
345 case SSH_CMSG_MAX_PACKET_SIZE:
346 if (packet_set_maxsize(packet_get_int()) > 0)
350 case SSH_CMSG_EXEC_SHELL:
351 case SSH_CMSG_EXEC_CMD:
352 /* Set interactive/non-interactive mode. */
353 packet_set_interactive(have_pty || s->display != NULL,
356 if (type == SSH_CMSG_EXEC_CMD) {
357 command = packet_get_string(&dlen);
358 debug("Exec command '%.500s'", command);
359 packet_integrity_check(plen, 4 + dlen, type);
362 packet_integrity_check(plen, 0, type);
364 if (forced_command != NULL) {
365 command = forced_command;
366 debug("Forced command '%.500s'", forced_command);
369 do_exec_pty(s, command, pw);
371 do_exec_no_pty(s, command, pw);
375 /* Cleanup user's local Xauthority file. */
377 xauthfile_cleanup_proc(NULL);
382 * Any unknown messages in this phase are ignored,
383 * and a failure message is returned.
385 log("Unknown packet type received after authentication: %d", type);
387 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
391 /* Enable compression now that we have replied if appropriate. */
392 if (enable_compression_after_reply) {
393 enable_compression_after_reply = 0;
394 packet_start_compression(compression_level);
400 * This is called to fork and execute a command when we have no tty. This
401 * will call do_child from the child, and server_loop from the parent after
402 * setting up file descriptors and such.
405 do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
410 int pin[2], pout[2], perr[2];
411 /* Allocate pipes for communicating with the program. */
412 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
413 packet_disconnect("Could not create pipes: %.100s",
415 #else /* USE_PIPES */
416 int inout[2], err[2];
417 /* Uses socket pairs to communicate with the program. */
418 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
419 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
420 packet_disconnect("Could not create socket pairs: %.100s",
422 #endif /* USE_PIPES */
424 fatal("do_exec_no_pty: no session");
426 session_proctitle(s);
432 /* Fork the child. */
433 if ((pid = fork()) == 0) {
434 /* Child. Reinitialize the log since the pid has changed. */
435 log_init(__progname, options.log_level, options.log_facility, log_stderr);
438 * Create a new session and process group since the 4.4BSD
439 * setlogin() affects the entire process group.
442 error("setsid failed: %.100s", strerror(errno));
446 * Redirect stdin. We close the parent side of the socket
447 * pair, and make the child side the standard input.
450 if (dup2(pin[0], 0) < 0)
451 perror("dup2 stdin");
454 /* Redirect stdout. */
456 if (dup2(pout[1], 1) < 0)
457 perror("dup2 stdout");
460 /* Redirect stderr. */
462 if (dup2(perr[1], 2) < 0)
463 perror("dup2 stderr");
465 #else /* USE_PIPES */
467 * Redirect stdin, stdout, and stderr. Stdin and stdout will
468 * use the same socket, as some programs (particularly rdist)
469 * seem to depend on it.
473 if (dup2(inout[0], 0) < 0) /* stdin */
474 perror("dup2 stdin");
475 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
476 perror("dup2 stdout");
477 if (dup2(err[0], 2) < 0) /* stderr */
478 perror("dup2 stderr");
479 #endif /* USE_PIPES */
481 /* Do processing for the child (exec command etc). */
482 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
486 packet_disconnect("fork failed: %.100s", strerror(errno));
489 /* We are the parent. Close the child sides of the pipes. */
495 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
497 /* Enter the interactive session. */
498 server_loop(pid, pin[1], pout[0], perr[0]);
499 /* server_loop has closed pin[1], pout[1], and perr[1]. */
501 #else /* USE_PIPES */
502 /* We are the parent. Close the child sides of the socket pairs. */
507 * Enter the interactive session. Note: server_loop must be able to
508 * handle the case that fdin and fdout are the same.
511 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
513 server_loop(pid, inout[1], inout[1], err[1]);
514 /* server_loop has closed inout[1] and err[1]. */
516 #endif /* USE_PIPES */
520 * This is called to fork and execute a command when we have a tty. This
521 * will call do_child from the child, and server_loop from the parent after
522 * setting up file descriptors, controlling tty, updating wtmp, utmp,
523 * lastlog, and other such operations.
526 do_exec_pty(Session *s, const char *command, struct passwd * pw)
528 int fdout, ptyfd, ttyfd, ptymaster;
532 fatal("do_exec_pty: no session");
537 do_pam_session(pw->pw_name, s->tty);
541 /* Fork the child. */
542 if ((pid = fork()) == 0) {
543 /* Child. Reinitialize the log because the pid has changed. */
544 log_init(__progname, options.log_level, options.log_facility, log_stderr);
546 /* Close the master side of the pseudo tty. */
549 /* Make the pseudo tty our controlling tty. */
550 pty_make_controlling_tty(&ttyfd, s->tty);
552 /* Redirect stdin from the pseudo tty. */
553 if (dup2(ttyfd, fileno(stdin)) < 0)
554 error("dup2 stdin failed: %.100s", strerror(errno));
556 /* Redirect stdout to the pseudo tty. */
557 if (dup2(ttyfd, fileno(stdout)) < 0)
558 error("dup2 stdin failed: %.100s", strerror(errno));
560 /* Redirect stderr to the pseudo tty. */
561 if (dup2(ttyfd, fileno(stderr)) < 0)
562 error("dup2 stdin failed: %.100s", strerror(errno));
564 /* Close the extra descriptor for the pseudo tty. */
567 /* record login, etc. similar to login(1) */
568 if (command == NULL && !options.use_login)
571 /* Do common processing for the child, such as execing the command. */
572 do_child(command, pw, s->term, s->display, s->auth_proto,
573 s->auth_data, s->tty);
577 packet_disconnect("fork failed: %.100s", strerror(errno));
580 /* Parent. Close the slave side of the pseudo tty. */
584 * Create another descriptor of the pty master side for use as the
585 * standard input. We could use the original descriptor, but this
586 * simplifies code in server_loop. The descriptor is bidirectional.
590 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
592 /* we keep a reference to the pty master */
593 ptymaster = dup(ptyfd);
595 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
596 s->ptymaster = ptymaster;
598 /* Enter interactive session. */
600 session_set_fds(s, ptyfd, fdout, -1);
602 server_loop(pid, ptyfd, fdout, -1);
603 /* server_loop _has_ closed ptyfd and fdout. */
604 session_pty_cleanup(s);
609 get_remote_name_or_ip(void)
611 static const char *remote = "";
613 remote = get_canonical_hostname();
614 if (utmp_len == 0 || strlen(remote) > utmp_len)
615 remote = get_remote_ipaddr();
619 /* administrative, login(1)-like work */
627 struct sockaddr_storage from;
629 time_t last_login_time;
630 struct passwd * pw = s->pw;
631 pid_t pid = getpid();
634 * Get IP address of client. If the connection is not a socket, let
635 * the address be 0.0.0.0.
637 memset(&from, 0, sizeof(from));
638 if (packet_connection_is_on_socket()) {
639 fromlen = sizeof(from);
640 if (getpeername(packet_get_connection_in(),
641 (struct sockaddr *) & from, &fromlen) < 0) {
642 debug("getpeername: %.100s", strerror(errno));
647 /* Record that there was a login on that tty from the remote host. */
648 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
649 get_remote_name_or_ip(), (struct sockaddr *)&from);
651 /* Done if .hushlogin exists. */
652 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
653 if (stat(buf, &st) >= 0)
657 print_pam_messages();
659 #ifdef WITH_AIXAUTHENTICATE
660 if (aixloginmsg && *aixloginmsg)
661 printf("%s\n", aixloginmsg);
662 #endif /* WITH_AIXAUTHENTICATE */
665 * Get the time when the user last logged in. 'buf' will be set
666 * to contain the hostname the last login was from.
668 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
670 if (last_login_time != 0) {
671 time_string = ctime(&last_login_time);
672 if (strchr(time_string, '\n'))
673 *strchr(time_string, '\n') = 0;
674 if (strcmp(buf, "") == 0)
675 printf("Last login: %s\r\n", time_string);
677 printf("Last login: %s from %s\r\n", time_string, buf);
679 if (options.print_motd) {
680 f = fopen("/etc/motd", "r");
682 while (fgets(buf, sizeof(buf), f))
690 * Sets the value of the given variable in the environment. If the variable
691 * already exists, its value is overriden.
694 child_set_env(char ***envp, unsigned int *envsizep, const char *name,
697 unsigned int i, namelen;
701 * Find the slot where the value should be stored. If the variable
702 * already exists, we reuse the slot; otherwise we append a new slot
703 * at the end of the array, expanding if necessary.
706 namelen = strlen(name);
707 for (i = 0; env[i]; i++)
708 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
711 /* Reuse the slot. */
714 /* New variable. Expand if necessary. */
715 if (i >= (*envsizep) - 1) {
717 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
719 /* Need to set the NULL pointer at end of array beyond the new slot. */
723 /* Allocate space and format the variable in the appropriate slot. */
724 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
725 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
729 * Reads environment variables from the given file and adds/overrides them
730 * into the environment. If the file does not exist, this does nothing.
731 * Otherwise, it must consist of empty lines, comments (line starts with '#')
732 * and assignments of the form name=value. No other forms are allowed.
735 read_environment_file(char ***env, unsigned int *envsize,
736 const char *filename)
742 f = fopen(filename, "r");
746 while (fgets(buf, sizeof(buf), f)) {
747 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
749 if (!*cp || *cp == '#' || *cp == '\n')
751 if (strchr(cp, '\n'))
752 *strchr(cp, '\n') = '\0';
753 value = strchr(cp, '=');
755 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
759 * Replace the equals sign by nul, and advance value to
764 child_set_env(env, envsize, cp, value);
771 * Sets any environment variables which have been specified by PAM
773 void do_pam_environment(char ***env, int *envsize)
775 char *equals, var_name[512], var_val[512];
779 if ((pam_env = fetch_pam_environment()) == NULL)
782 for(i = 0; pam_env[i] != NULL; i++) {
783 if ((equals = strstr(pam_env[i], "=")) == NULL)
786 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
787 memset(var_name, '\0', sizeof(var_name));
788 memset(var_val, '\0', sizeof(var_val));
790 strncpy(var_name, pam_env[i], equals - pam_env[i]);
791 strcpy(var_val, equals + 1);
793 debug("PAM environment: %s=%s", var_name, var_val);
795 child_set_env(env, envsize, var_name, var_val);
801 #if defined(HAVE_GETUSERATTR)
803 * AIX-specific login initialisation
805 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
810 getrlimit(resource, &rlim);
813 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
815 rlim.rlim_cur = RLIM_INFINITY;
816 } else if (slim != 0) {
817 /* See the wackiness below */
818 if (rlim.rlim_cur == slim * mult)
821 rlim.rlim_cur = slim * mult;
826 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
828 rlim.rlim_max = RLIM_INFINITY;
829 } else if (hlim != 0) {
830 rlim.rlim_max = hlim * mult;
835 * XXX For cpu and fsize the soft limit is set to the hard limit
836 * if the hard limit is left at its default value and the soft limit
837 * is changed from its default value, either by requesting it
838 * (slim == 0) or by setting it to the current default. At least
839 * that's how rlogind does it. If you're confused you're not alone.
840 * Bug or feature? AIX 4.3.1.2
842 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
843 && hlim == 0 && slim != 0)
844 rlim.rlim_max = rlim.rlim_cur;
845 /* A specified hard limit limits the soft limit */
846 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
847 rlim.rlim_cur = rlim.rlim_max;
848 /* A soft limit can increase a hard limit */
849 else if (rlim.rlim_cur > rlim.rlim_max)
850 rlim.rlim_max = rlim.rlim_cur;
852 if (setrlimit(resource, &rlim) != 0)
853 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
856 void set_limits_from_userattr(char *user)
861 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
862 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
863 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
864 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
865 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
866 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
867 #if defined(S_UNOFILE)
868 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
871 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
872 /* Convert decimal to octal */
873 (void) snprintf(buf, sizeof(buf), "%d", mask);
874 if (sscanf(buf, "%o", &mask) == 1)
878 #endif /* defined(HAVE_GETUSERATTR) */
881 * Performs common processing for the child, such as setting up the
882 * environment, closing extra file descriptors, setting the user and group
883 * ids, and executing the command or shell.
886 do_child(const char *command, struct passwd * pw, const char *term,
887 const char *display, const char *auth_proto,
888 const char *auth_data, const char *ttyname)
890 const char *shell, *cp = NULL;
894 unsigned int envsize, i;
896 extern char **environ;
899 #ifdef WITH_IRIX_PROJECT
901 #endif /* WITH_IRIX_PROJECT */
903 /* login(1) is only called if we execute the login shell */
904 if (options.use_login && command != NULL)
905 options.use_login = 0;
907 #ifndef USE_PAM /* pam_nologin handles this */
908 f = fopen("/etc/nologin", "r");
910 /* /etc/nologin exists. Print its contents and exit. */
911 while (fgets(buf, sizeof(buf), f))
920 /* Set login name in the kernel. */
921 if (setlogin(pw->pw_name) < 0)
922 error("setlogin failed: %s", strerror(errno));
925 /* Set uid, gid, and groups. */
926 /* Login(1) does this as well, and it needs uid 0 for the "-h"
927 switch, so we let login(1) to this for us. */
928 if (!options.use_login) {
930 extern char **saved_argv;
931 extern int saved_argc;
932 char *host = get_canonical_hostname ();
934 if (sia_become_user(NULL, saved_argc, saved_argv, host,
935 pw->pw_name, ttyname, 0, NULL, NULL, SIA_BEU_SETLUID) !=
937 perror("sia_become_user");
940 if (setreuid(geteuid(), geteuid()) < 0) {
944 #else /* HAVE_OSF_SIA */
945 if (getuid() == 0 || geteuid() == 0) {
946 #if defined(HAVE_GETUSERATTR)
947 set_limits_from_userattr(pw->pw_name);
948 #endif /* defined(HAVE_GETUSERATTR) */
950 if (setgid(pw->pw_gid) < 0) {
954 /* Initialize the group list. */
955 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
956 perror("initgroups");
961 #ifdef WITH_IRIX_ARRAY
962 /* initialize array session */
963 if (newarraysess() != 0)
964 fatal("Failed to set up new array session: %.100s",
966 #endif /* WITH_IRIX_ARRAY */
968 #ifdef WITH_IRIX_PROJECT
969 /* initialize irix project info */
970 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
971 debug("Failed to get project id, using projid 0");
976 fatal("Failed to initialize project %d for %s: %.100s",
977 (int)projid, pw->pw_name, strerror(errno));
978 #endif /* WITH_IRIX_PROJECT */
980 /* Permanently switch to the desired uid. */
981 permanently_set_uid(pw->pw_uid);
983 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
984 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
985 #endif /* HAVE_OSF_SIA */
988 * Get the shell from the password data. An empty shell field is
989 * legal, and means /bin/sh.
991 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
994 /* Try to get AFS tokens for the local cell. */
998 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1005 /* Initialize the environment. */
1007 env = xmalloc(envsize * sizeof(char *));
1010 if (!options.use_login) {
1011 /* Set basic environment. */
1012 child_set_env(&env, &envsize, "USER", pw->pw_name);
1013 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1014 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1015 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1017 snprintf(buf, sizeof buf, "%.200s/%.50s",
1018 _PATH_MAILDIR, pw->pw_name);
1019 child_set_env(&env, &envsize, "MAIL", buf);
1021 /* Normal systems set SHELL by default. */
1022 child_set_env(&env, &envsize, "SHELL", shell);
1025 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1027 /* Set custom environment options from RSA authentication. */
1028 while (custom_environment) {
1029 struct envstring *ce = custom_environment;
1032 for (i = 0; s[i] != '=' && s[i]; i++);
1035 child_set_env(&env, &envsize, s, s + i + 1);
1037 custom_environment = ce->next;
1042 snprintf(buf, sizeof buf, "%.50s %d %d",
1043 get_remote_ipaddr(), get_remote_port(), get_local_port());
1044 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1047 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
1049 child_set_env(&env, &envsize, "TERM", term);
1051 child_set_env(&env, &envsize, "DISPLAY", display);
1055 char *authstate,*krb5cc;
1057 if ((authstate = getenv("AUTHSTATE")) != NULL)
1058 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
1060 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
1061 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
1067 extern char *ticket;
1070 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1075 /* Pull in any environment variables that may have been set by PAM. */
1076 do_pam_environment(&env, &envsize);
1077 #endif /* USE_PAM */
1079 read_environment_file(&env,&envsize,"/etc/environment");
1082 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1083 if (auth_get_socket_name() != NULL)
1084 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1085 auth_get_socket_name());
1087 /* read $HOME/.ssh/environment. */
1088 if (!options.use_login) {
1089 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1091 read_environment_file(&env, &envsize, buf);
1094 /* dump the environment */
1095 fprintf(stderr, "Environment:\n");
1096 for (i = 0; env[i]; i++)
1097 fprintf(stderr, " %.200s\n", env[i]);
1100 * Close the connection descriptors; note that this is the child, and
1101 * the server will still have the socket open, and it is important
1102 * that we do not shutdown it. Note that the descriptors cannot be
1103 * closed before building the environment, as we call
1104 * get_remote_ipaddr there.
1106 if (packet_get_connection_in() == packet_get_connection_out())
1107 close(packet_get_connection_in());
1109 close(packet_get_connection_in());
1110 close(packet_get_connection_out());
1113 * Close all descriptors related to channels. They will still remain
1114 * open in the parent.
1116 /* XXX better use close-on-exec? -markus */
1117 channel_close_all();
1120 * Close any extra file descriptors. Note that there may still be
1121 * descriptors left by system functions. They will be closed later.
1126 * Close any extra open file descriptors so that we don\'t have them
1127 * hanging around in clients. Note that we want to do this after
1128 * initgroups, because at least on Solaris 2.3 it leaves file
1131 for (i = 3; i < 64; i++)
1134 /* Change current directory to the user\'s home directory. */
1135 if (chdir(pw->pw_dir) < 0)
1136 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1137 pw->pw_dir, strerror(errno));
1140 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1141 * xauth are run in the proper environment.
1146 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1149 if (!options.use_login) {
1150 if (stat(SSH_USER_RC, &st) >= 0) {
1152 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_USER_RC);
1154 f = popen(_PATH_BSHELL " " SSH_USER_RC, "w");
1156 if (auth_proto != NULL && auth_data != NULL)
1157 fprintf(f, "%s %s\n", auth_proto, auth_data);
1160 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1161 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1163 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_SYSTEM_RC);
1165 f = popen(_PATH_BSHELL " " SSH_SYSTEM_RC, "w");
1167 if (auth_proto != NULL && auth_data != NULL)
1168 fprintf(f, "%s %s\n", auth_proto, auth_data);
1171 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
1172 } else if (options.xauth_location != NULL) {
1173 /* Add authority data to .Xauthority if appropriate. */
1174 if (auth_proto != NULL && auth_data != NULL) {
1175 char *screen = strchr(display, ':');
1178 "Running %.100s add %.100s %.100s %.100s\n",
1179 options.xauth_location, display,
1180 auth_proto, auth_data);
1183 "Adding %.*s/unix%s %s %s\n",
1184 screen-display, display,
1185 screen, auth_proto, auth_data);
1187 snprintf(cmd, sizeof cmd, "%s -q -",
1188 options.xauth_location);
1189 f = popen(cmd, "w");
1191 fprintf(f, "add %s %s %s\n", display,
1192 auth_proto, auth_data);
1194 fprintf(f, "add %.*s/unix%s %s %s\n",
1195 screen-display, display,
1196 screen, auth_proto, auth_data);
1199 fprintf(stderr, "Could not run %s\n",
1204 /* Get the last component of the shell name. */
1205 cp = strrchr(shell, '/');
1212 * If we have no command, execute the shell. In this case, the shell
1213 * name to be passed in argv[0] is preceded by '-' to indicate that
1214 * this is a login shell.
1217 if (!options.use_login) {
1221 * Check for mail if we have a tty and it was enabled
1222 * in server options.
1224 if (ttyname && options.check_mail) {
1226 struct stat mailstat;
1227 mailbox = getenv("MAIL");
1228 if (mailbox != NULL) {
1229 if (stat(mailbox, &mailstat) != 0 ||
1230 mailstat.st_size == 0)
1231 printf("No mail.\n");
1232 else if (mailstat.st_mtime < mailstat.st_atime)
1233 printf("You have mail.\n");
1235 printf("You have new mail.\n");
1238 /* Start the shell. Set initial character to '-'. */
1240 strncpy(buf + 1, cp, sizeof(buf) - 1);
1241 buf[sizeof(buf) - 1] = 0;
1243 /* Execute the shell. */
1246 execve(shell, argv, env);
1248 /* Executing the shell failed. */
1253 /* Launch login(1). */
1255 execl(LOGIN_PROGRAM, "login",
1256 "-h", get_remote_name_or_ip(),
1257 "-p", "-f", "--", pw->pw_name, NULL);
1259 /* Login couldn't be executed, die. */
1266 * Execute the command using the user's shell. This uses the -c
1267 * option to execute the command.
1269 argv[0] = (char *) cp;
1271 argv[2] = (char *) command;
1273 execve(shell, argv, env);
1282 static int did_init = 0;
1284 debug("session_new: init");
1285 for(i = 0; i < MAX_SESSIONS; i++) {
1286 sessions[i].used = 0;
1287 sessions[i].self = i;
1291 for(i = 0; i < MAX_SESSIONS; i++) {
1292 Session *s = &sessions[i];
1303 s->auth_data = NULL;
1304 s->auth_proto = NULL;
1307 debug("session_new: session %d", i);
1318 for(i = 0; i < MAX_SESSIONS; i++) {
1319 Session *s = &sessions[i];
1320 debug("dump: used %d session %d %p channel %d pid %d",
1330 session_open(int chanid)
1332 Session *s = session_new();
1333 debug("session_open: channel %d", chanid);
1335 error("no more sessions");
1338 s->pw = auth_get_user();
1340 fatal("no user for session %i", s->self);
1341 debug("session_open: session %d: link with channel %d", s->self, chanid);
1347 session_by_channel(int id)
1350 for(i = 0; i < MAX_SESSIONS; i++) {
1351 Session *s = &sessions[i];
1352 if (s->used && s->chanid == id) {
1353 debug("session_by_channel: session %d channel %d", i, id);
1357 debug("session_by_channel: unknown channel %d", id);
1363 session_by_pid(pid_t pid)
1366 debug("session_by_pid: pid %d", pid);
1367 for(i = 0; i < MAX_SESSIONS; i++) {
1368 Session *s = &sessions[i];
1369 if (s->used && s->pid == pid)
1372 error("session_by_pid: unknown pid %d", pid);
1378 session_window_change_req(Session *s)
1380 s->col = packet_get_int();
1381 s->row = packet_get_int();
1382 s->xpixel = packet_get_int();
1383 s->ypixel = packet_get_int();
1385 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1390 session_pty_req(Session *s)
1393 char *term_modes; /* encoded terminal modes */
1399 s->term = packet_get_string(&len);
1400 s->col = packet_get_int();
1401 s->row = packet_get_int();
1402 s->xpixel = packet_get_int();
1403 s->ypixel = packet_get_int();
1404 term_modes = packet_get_string(&len);
1407 if (strcmp(s->term, "") == 0) {
1411 /* Allocate a pty and open it. */
1412 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1417 error("session_pty_req: session %d alloc failed", s->self);
1421 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1423 * Add a cleanup function to clear the utmp entry and record logout
1424 * time in case we call fatal() (e.g., the connection gets closed).
1426 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1427 pty_setowner(s->pw, s->tty);
1428 /* Get window size from the packet. */
1429 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1431 session_proctitle(s);
1433 /* XXX parse and set terminal modes */
1439 session_subsystem_req(Session *s)
1443 char *subsys = packet_get_string(&len);
1447 log("subsystem request for %s", subsys);
1449 for (i = 0; i < options.num_subsystems; i++) {
1450 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1451 debug("subsystem: exec() %s", options.subsystem_command[i]);
1452 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1458 log("subsystem request for %s failed, subsystem not found", subsys);
1465 session_x11_req(Session *s)
1467 if (no_x11_forwarding_flag) {
1468 debug("X11 forwarding disabled in user configuration file.");
1471 if (!options.x11_forwarding) {
1472 debug("X11 forwarding disabled in server configuration file.");
1475 if (xauthfile != NULL) {
1476 debug("X11 fwd already started.");
1480 debug("Received request for X11 forwarding with auth spoofing.");
1481 if (s->display != NULL)
1482 packet_disconnect("Protocol error: X11 display already set.");
1484 s->single_connection = packet_get_char();
1485 s->auth_proto = packet_get_string(NULL);
1486 s->auth_data = packet_get_string(NULL);
1487 s->screen = packet_get_int();
1490 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1491 if (s->display == NULL) {
1492 xfree(s->auth_proto);
1493 xfree(s->auth_data);
1496 xauthfile = xmalloc(MAXPATHLEN);
1497 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1498 temporarily_use_uid(s->pw->pw_uid);
1499 if (mkdtemp(xauthfile) == NULL) {
1501 error("private X11 dir: mkdtemp %s failed: %s",
1502 xauthfile, strerror(errno));
1505 xfree(s->auth_proto);
1506 xfree(s->auth_data);
1507 /* XXXX remove listening channels */
1510 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1511 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1513 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1518 session_shell_req(Session *s)
1520 /* if forced_command == NULL, the shell is execed */
1521 char *shell = forced_command;
1525 do_exec_no_pty(s, shell, s->pw);
1527 do_exec_pty(s, shell, s->pw);
1532 session_exec_req(Session *s)
1535 char *command = packet_get_string(&len);
1537 if (forced_command) {
1539 command = forced_command;
1540 debug("Forced command '%.500s'", forced_command);
1544 do_exec_no_pty(s, command, s->pw);
1546 do_exec_pty(s, command, s->pw);
1547 if (forced_command == NULL)
1553 session_input_channel_req(int id, void *arg)
1562 rtype = packet_get_string(&len);
1563 reply = packet_get_char();
1565 s = session_by_channel(id);
1567 fatal("session_input_channel_req: channel %d: no session", id);
1568 c = channel_lookup(id);
1570 fatal("session_input_channel_req: channel %d: bad channel", id);
1572 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1573 s->self, id, rtype, reply);
1576 * a session is in LARVAL state until a shell
1577 * or programm is executed
1579 if (c->type == SSH_CHANNEL_LARVAL) {
1580 if (strcmp(rtype, "shell") == 0) {
1581 success = session_shell_req(s);
1582 } else if (strcmp(rtype, "exec") == 0) {
1583 success = session_exec_req(s);
1584 } else if (strcmp(rtype, "pty-req") == 0) {
1585 success = session_pty_req(s);
1586 } else if (strcmp(rtype, "x11-req") == 0) {
1587 success = session_x11_req(s);
1588 } else if (strcmp(rtype, "subsystem") == 0) {
1589 success = session_subsystem_req(s);
1592 if (strcmp(rtype, "window-change") == 0) {
1593 success = session_window_change_req(s);
1597 packet_start(success ?
1598 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1599 packet_put_int(c->remote_id);
1606 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1609 fatal("session_set_fds: called for proto != 2.0");
1611 * now that have a child and a pipe to the child,
1612 * we can activate our channel and register the fd's
1614 if (s->chanid == -1)
1615 fatal("no channel for session %d", s->self);
1616 channel_set_fds(s->chanid,
1618 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1622 session_pty_cleanup(Session *s)
1624 if (s == NULL || s->ttyfd == -1)
1627 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1629 /* Cancel the cleanup function. */
1630 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1632 /* Record that the user has logged out. */
1633 record_logout(s->pid, s->tty);
1635 /* Release the pseudo-tty. */
1636 pty_release(s->tty);
1639 * Close the server side of the socket pairs. We must do this after
1640 * the pty cleanup, so that another process doesn't get this pty
1641 * while we're still cleaning up.
1643 if (close(s->ptymaster) < 0)
1644 error("close(s->ptymaster): %s", strerror(errno));
1648 session_exit_message(Session *s, int status)
1652 fatal("session_close: no session");
1653 c = channel_lookup(s->chanid);
1655 fatal("session_close: session %d: no channel %d",
1656 s->self, s->chanid);
1657 debug("session_exit_message: session %d channel %d pid %d",
1658 s->self, s->chanid, s->pid);
1660 if (WIFEXITED(status)) {
1661 channel_request_start(s->chanid,
1663 packet_put_int(WEXITSTATUS(status));
1665 } else if (WIFSIGNALED(status)) {
1666 channel_request_start(s->chanid,
1668 packet_put_int(WTERMSIG(status));
1670 packet_put_char(WCOREDUMP(status));
1671 #else /* WCOREDUMP */
1673 #endif /* WCOREDUMP */
1674 packet_put_cstring("");
1675 packet_put_cstring("");
1678 /* Some weird exit cause. Just exit. */
1679 packet_disconnect("wait returned status %04x.", status);
1682 /* disconnect channel */
1683 debug("session_exit_message: release channel %d", s->chanid);
1684 channel_cancel_cleanup(s->chanid);
1686 * emulate a write failure with 'chan_write_failed', nobody will be
1687 * interested in data we write.
1688 * Note that we must not call 'chan_read_failed', since there could
1689 * be some more data waiting in the pipe.
1691 if (c->ostate != CHAN_OUTPUT_CLOSED)
1692 chan_write_failed(c);
1697 session_free(Session *s)
1699 debug("session_free: session %d pid %d", s->self, s->pid);
1705 xfree(s->auth_data);
1707 xfree(s->auth_proto);
1712 session_close(Session *s)
1714 session_pty_cleanup(s);
1716 session_proctitle(s);
1720 session_close_by_pid(pid_t pid, int status)
1722 Session *s = session_by_pid(pid);
1724 debug("session_close_by_pid: no session for pid %d", s->pid);
1727 if (s->chanid != -1)
1728 session_exit_message(s, status);
1733 * this is called when a channel dies before
1734 * the session 'child' itself dies
1737 session_close_by_channel(int id, void *arg)
1739 Session *s = session_by_channel(id);
1741 debug("session_close_by_channel: no session for channel %d", id);
1744 /* disconnect channel */
1745 channel_cancel_cleanup(s->chanid);
1748 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1750 /* close session immediately */
1753 /* notify child, delay session cleanup */
1755 fatal("session_close_by_channel: Unsafe s->pid = %d", s->pid);
1756 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1757 error("session_close_by_channel: kill %d: %s",
1758 s->pid, strerror(errno));
1763 session_tty_list(void)
1765 static char buf[1024];
1768 for(i = 0; i < MAX_SESSIONS; i++) {
1769 Session *s = &sessions[i];
1770 if (s->used && s->ttyfd != -1) {
1772 strlcat(buf, ",", sizeof buf);
1773 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1777 strlcpy(buf, "notty", sizeof buf);
1782 session_proctitle(Session *s)
1785 error("no user for session %d", s->self);
1787 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1791 do_authenticated2(void)
1794 * Cancel the alarm we set to limit the time taken for
1798 if (startup_pipe != -1) {
1799 close(startup_pipe);
1804 xauthfile_cleanup_proc(NULL);