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.35 2000/09/04 19:07:21 markus Exp $");
29 #include "auth-options.h"
31 #ifdef WITH_IRIX_PROJECT
33 #endif /* WITH_IRIX_PROJECT */
35 #if defined(HAVE_USERSEC_H)
46 #include <sys/cygwin.h>
47 #define is_winnt (GetVersion() < 0x80000000)
51 #if defined(HAVE_GETUSERATTR) && !defined(S_UFSIZE_HARD) && defined(S_UFSIZE)
52 # define S_UFSIZE_HARD S_UFSIZE "_hard"
53 # define S_UCPU_HARD S_UCPU "_hard"
54 # define S_UDATA_HARD S_UDATA "_hard"
55 # define S_USTACK_HARD S_USTACK "_hard"
56 # define S_URSS_HARD S_URSS "_hard"
57 # define S_UCORE_HARD S_UCORE "_hard"
58 # define S_UNOFILE_HARD S_UNOFILE "_hard"
62 #include <login_cap.h>
68 typedef struct Session Session;
77 int ptyfd, ttyfd, ptymaster;
78 int row, col, xpixel, ypixel;
85 int single_connection;
92 Session *session_new(void);
93 void session_set_fds(Session *s, int fdin, int fdout, int fderr);
94 void session_pty_cleanup(Session *s);
95 void session_proctitle(Session *s);
96 void do_exec_pty(Session *s, const char *command, struct passwd * pw);
97 void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
98 void do_login(Session *s);
101 do_child(const char *command, struct passwd * pw, const char *term,
102 const char *display, const char *auth_proto,
103 const char *auth_data, const char *ttyname);
106 extern ServerOptions options;
107 #ifdef HAVE___PROGNAME
108 extern char *__progname;
109 #else /* HAVE___PROGNAME */
110 static const char *__progname = "sshd";
111 #endif /* HAVE___PROGNAME */
113 extern int log_stderr;
114 extern int debug_flag;
115 extern unsigned int utmp_len;
117 extern int startup_pipe;
119 /* Local Xauthority file. */
120 static char *xauthfile;
122 /* original command from peer. */
123 char *original_command = NULL;
126 #define MAX_SESSIONS 10
127 Session sessions[MAX_SESSIONS];
128 #ifdef WITH_AIXAUTHENTICATE
129 /* AIX's lastlogin message, set in auth1.c */
131 #endif /* WITH_AIXAUTHENTICATE */
133 #ifdef HAVE_LOGIN_CAP
134 static login_cap_t *lc;
138 * Remove local Xauthority file.
141 xauthfile_cleanup_proc(void *ignore)
143 debug("xauthfile_cleanup_proc called");
145 if (xauthfile != NULL) {
148 p = strrchr(xauthfile, '/');
159 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
160 * dropped connection).
163 pty_cleanup_proc(void *session)
167 fatal("pty_cleanup_proc: no session");
168 debug("pty_cleanup_proc: %s", s->tty);
171 /* Record that the user has logged out. */
172 record_logout(s->pid, s->tty);
175 /* Release the pseudo-tty. */
180 * Prepares for an interactive session. This is called after the user has
181 * been successfully authenticated. During this message exchange, pseudo
182 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
183 * are requested, etc.
186 do_authenticated(struct passwd * pw)
190 int compression_level = 0, enable_compression_after_reply = 0;
195 unsigned int proto_len, data_len, dlen;
198 * Cancel the alarm we set to limit the time taken for
202 if (startup_pipe != -1) {
208 * Inform the channel mechanism that we are the server side and that
209 * the client may request to connect to any port at all. (The user
210 * could do it anyway, and we wouldn\'t know what is permitted except
211 * by the client telling us, so we can equally well trust the client
212 * not to request anything bogus.)
214 if (!no_port_forwarding_flag)
215 channel_permit_all_opens();
220 #ifdef HAVE_LOGIN_CAP
221 if ((lc = login_getclass(pw->pw_class)) == NULL) {
222 error("unable to get login class");
228 * We stay in this loop until the client requests to execute a shell
234 /* Get a packet from the client. */
235 type = packet_read(&plen);
237 /* Process the packet. */
239 case SSH_CMSG_REQUEST_COMPRESSION:
240 packet_integrity_check(plen, 4, type);
241 compression_level = packet_get_int();
242 if (compression_level < 1 || compression_level > 9) {
243 packet_send_debug("Received illegal compression level %d.",
247 /* Enable compression after we have responded with SUCCESS. */
248 enable_compression_after_reply = 1;
252 case SSH_CMSG_REQUEST_PTY:
254 debug("Allocating a pty not permitted for this authentication.");
258 packet_disconnect("Protocol error: you already have a pty.");
260 debug("Allocating pty.");
262 /* Allocate a pty and open it. */
263 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
265 error("Failed to allocate pty.");
268 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
269 pty_setowner(pw, s->tty);
271 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
272 s->term = packet_get_string(&dlen);
273 packet_integrity_check(dlen, strlen(s->term), type);
274 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
275 /* Remaining bytes */
276 n_bytes = plen - (4 + dlen + 4 * 4);
278 if (strcmp(s->term, "") == 0) {
282 /* Get window size from the packet. */
283 s->row = packet_get_int();
284 s->col = packet_get_int();
285 s->xpixel = packet_get_int();
286 s->ypixel = packet_get_int();
287 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
289 /* Get tty modes from the packet. */
290 tty_parse_modes(s->ttyfd, &n_bytes);
291 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
293 session_proctitle(s);
295 /* Indicate that we now have a pty. */
300 case SSH_CMSG_X11_REQUEST_FORWARDING:
301 if (!options.x11_forwarding) {
302 packet_send_debug("X11 forwarding disabled in server configuration file.");
305 if (!options.xauth_location) {
306 packet_send_debug("No xauth program; cannot forward with spoofing.");
309 if (no_x11_forwarding_flag) {
310 packet_send_debug("X11 forwarding not permitted for this authentication.");
313 debug("Received request for X11 forwarding with auth spoofing.");
314 if (s->display != NULL)
315 packet_disconnect("Protocol error: X11 display already set.");
317 s->auth_proto = packet_get_string(&proto_len);
318 s->auth_data = packet_get_string(&data_len);
319 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
321 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
322 s->screen = packet_get_int();
325 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
327 if (s->display == NULL)
330 /* Setup to always have a local .Xauthority. */
331 xauthfile = xmalloc(MAXPATHLEN);
332 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
333 temporarily_use_uid(pw->pw_uid);
334 if (mkdtemp(xauthfile) == NULL) {
336 error("private X11 dir: mkdtemp %s failed: %s",
337 xauthfile, strerror(errno));
340 /* XXXX remove listening channels */
343 strlcat(xauthfile, "/cookies", MAXPATHLEN);
344 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
348 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
352 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
353 if (no_agent_forwarding_flag || compat13) {
354 debug("Authentication agent forwarding not permitted for this authentication.");
357 debug("Received authentication agent forwarding request.");
358 success = auth_input_request_forwarding(pw);
361 case SSH_CMSG_PORT_FORWARD_REQUEST:
362 if (no_port_forwarding_flag) {
363 debug("Port forwarding not permitted for this authentication.");
366 debug("Received TCP/IP port forwarding request.");
367 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
371 case SSH_CMSG_MAX_PACKET_SIZE:
372 if (packet_set_maxsize(packet_get_int()) > 0)
376 case SSH_CMSG_EXEC_SHELL:
377 case SSH_CMSG_EXEC_CMD:
378 /* Set interactive/non-interactive mode. */
379 packet_set_interactive(have_pty || s->display != NULL,
382 if (type == SSH_CMSG_EXEC_CMD) {
383 command = packet_get_string(&dlen);
384 debug("Exec command '%.500s'", command);
385 packet_integrity_check(plen, 4 + dlen, type);
388 packet_integrity_check(plen, 0, type);
390 if (forced_command != NULL) {
391 original_command = command;
392 command = forced_command;
393 debug("Forced command '%.500s'", forced_command);
396 do_exec_pty(s, command, pw);
398 do_exec_no_pty(s, command, pw);
402 /* Cleanup user's local Xauthority file. */
404 xauthfile_cleanup_proc(NULL);
409 * Any unknown messages in this phase are ignored,
410 * and a failure message is returned.
412 log("Unknown packet type received after authentication: %d", type);
414 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
418 /* Enable compression now that we have replied if appropriate. */
419 if (enable_compression_after_reply) {
420 enable_compression_after_reply = 0;
421 packet_start_compression(compression_level);
427 * This is called to fork and execute a command when we have no tty. This
428 * will call do_child from the child, and server_loop from the parent after
429 * setting up file descriptors and such.
432 do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
437 int pin[2], pout[2], perr[2];
438 /* Allocate pipes for communicating with the program. */
439 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
440 packet_disconnect("Could not create pipes: %.100s",
442 #else /* USE_PIPES */
443 int inout[2], err[2];
444 /* Uses socket pairs to communicate with the program. */
445 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
446 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
447 packet_disconnect("Could not create socket pairs: %.100s",
449 #endif /* USE_PIPES */
451 fatal("do_exec_no_pty: no session");
453 session_proctitle(s);
459 /* Fork the child. */
460 if ((pid = fork()) == 0) {
461 /* Child. Reinitialize the log since the pid has changed. */
462 log_init(__progname, options.log_level, options.log_facility, log_stderr);
465 * Create a new session and process group since the 4.4BSD
466 * setlogin() affects the entire process group.
469 error("setsid failed: %.100s", strerror(errno));
473 * Redirect stdin. We close the parent side of the socket
474 * pair, and make the child side the standard input.
477 if (dup2(pin[0], 0) < 0)
478 perror("dup2 stdin");
481 /* Redirect stdout. */
483 if (dup2(pout[1], 1) < 0)
484 perror("dup2 stdout");
487 /* Redirect stderr. */
489 if (dup2(perr[1], 2) < 0)
490 perror("dup2 stderr");
492 #else /* USE_PIPES */
494 * Redirect stdin, stdout, and stderr. Stdin and stdout will
495 * use the same socket, as some programs (particularly rdist)
496 * seem to depend on it.
500 if (dup2(inout[0], 0) < 0) /* stdin */
501 perror("dup2 stdin");
502 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
503 perror("dup2 stdout");
504 if (dup2(err[0], 2) < 0) /* stderr */
505 perror("dup2 stderr");
506 #endif /* USE_PIPES */
508 /* Do processing for the child (exec command etc). */
509 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
514 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
517 packet_disconnect("fork failed: %.100s", strerror(errno));
520 /* We are the parent. Close the child sides of the pipes. */
526 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
528 /* Enter the interactive session. */
529 server_loop(pid, pin[1], pout[0], perr[0]);
530 /* server_loop has closed pin[1], pout[1], and perr[1]. */
532 #else /* USE_PIPES */
533 /* We are the parent. Close the child sides of the socket pairs. */
538 * Enter the interactive session. Note: server_loop must be able to
539 * handle the case that fdin and fdout are the same.
542 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
544 server_loop(pid, inout[1], inout[1], err[1]);
545 /* server_loop has closed inout[1] and err[1]. */
547 #endif /* USE_PIPES */
551 * This is called to fork and execute a command when we have a tty. This
552 * will call do_child from the child, and server_loop from the parent after
553 * setting up file descriptors, controlling tty, updating wtmp, utmp,
554 * lastlog, and other such operations.
557 do_exec_pty(Session *s, const char *command, struct passwd * pw)
559 int fdout, ptyfd, ttyfd, ptymaster;
563 fatal("do_exec_pty: no session");
568 do_pam_session(pw->pw_name, s->tty);
572 /* Fork the child. */
573 if ((pid = fork()) == 0) {
574 /* Child. Reinitialize the log because the pid has changed. */
575 log_init(__progname, options.log_level, options.log_facility, log_stderr);
577 /* Close the master side of the pseudo tty. */
580 /* Make the pseudo tty our controlling tty. */
581 pty_make_controlling_tty(&ttyfd, s->tty);
583 /* Redirect stdin from the pseudo tty. */
584 if (dup2(ttyfd, fileno(stdin)) < 0)
585 error("dup2 stdin failed: %.100s", strerror(errno));
587 /* Redirect stdout to the pseudo tty. */
588 if (dup2(ttyfd, fileno(stdout)) < 0)
589 error("dup2 stdin failed: %.100s", strerror(errno));
591 /* Redirect stderr to the pseudo tty. */
592 if (dup2(ttyfd, fileno(stderr)) < 0)
593 error("dup2 stdin failed: %.100s", strerror(errno));
595 /* Close the extra descriptor for the pseudo tty. */
598 /* record login, etc. similar to login(1) */
599 if (command == NULL && !options.use_login)
602 /* Do common processing for the child, such as execing the command. */
603 do_child(command, pw, s->term, s->display, s->auth_proto,
604 s->auth_data, s->tty);
609 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
612 packet_disconnect("fork failed: %.100s", strerror(errno));
615 /* Parent. Close the slave side of the pseudo tty. */
619 * Create another descriptor of the pty master side for use as the
620 * standard input. We could use the original descriptor, but this
621 * simplifies code in server_loop. The descriptor is bidirectional.
625 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
627 /* we keep a reference to the pty master */
628 ptymaster = dup(ptyfd);
630 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
631 s->ptymaster = ptymaster;
633 /* Enter interactive session. */
635 session_set_fds(s, ptyfd, fdout, -1);
637 server_loop(pid, ptyfd, fdout, -1);
638 /* server_loop _has_ closed ptyfd and fdout. */
639 session_pty_cleanup(s);
644 get_remote_name_or_ip(void)
646 static const char *remote = "";
648 remote = get_canonical_hostname();
649 if (utmp_len == 0 || strlen(remote) > utmp_len)
650 remote = get_remote_ipaddr();
654 /* administrative, login(1)-like work */
661 char hostname[MAXHOSTNAMELEN];
663 struct sockaddr_storage from;
665 time_t last_login_time;
666 struct passwd * pw = s->pw;
667 pid_t pid = getpid();
670 * Get IP address of client. If the connection is not a socket, let
671 * the address be 0.0.0.0.
673 memset(&from, 0, sizeof(from));
674 if (packet_connection_is_on_socket()) {
675 fromlen = sizeof(from);
676 if (getpeername(packet_get_connection_in(),
677 (struct sockaddr *) & from, &fromlen) < 0) {
678 debug("getpeername: %.100s", strerror(errno));
683 /* Get the time and hostname when the user last logged in. */
684 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
685 hostname, sizeof(hostname));
687 /* Record that there was a login on that tty from the remote host. */
688 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
689 get_remote_name_or_ip(), (struct sockaddr *)&from);
691 /* Done if .hushlogin exists. */
692 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
693 #ifdef HAVE_LOGIN_CAP
694 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
696 if (stat(buf, &st) >= 0)
701 print_pam_messages();
703 #ifdef WITH_AIXAUTHENTICATE
704 if (aixloginmsg && *aixloginmsg)
705 printf("%s\n", aixloginmsg);
706 #endif /* WITH_AIXAUTHENTICATE */
708 if (last_login_time != 0) {
709 time_string = ctime(&last_login_time);
710 if (strchr(time_string, '\n'))
711 *strchr(time_string, '\n') = 0;
712 if (strcmp(buf, "") == 0)
713 printf("Last login: %s\r\n", time_string);
715 printf("Last login: %s from %s\r\n", time_string, buf);
717 if (options.print_motd) {
718 #ifdef HAVE_LOGIN_CAP
719 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
722 f = fopen("/etc/motd", "r");
725 while (fgets(buf, sizeof(buf), f))
733 * Sets the value of the given variable in the environment. If the variable
734 * already exists, its value is overriden.
737 child_set_env(char ***envp, unsigned int *envsizep, const char *name,
740 unsigned int i, namelen;
744 * Find the slot where the value should be stored. If the variable
745 * already exists, we reuse the slot; otherwise we append a new slot
746 * at the end of the array, expanding if necessary.
749 namelen = strlen(name);
750 for (i = 0; env[i]; i++)
751 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
754 /* Reuse the slot. */
757 /* New variable. Expand if necessary. */
758 if (i >= (*envsizep) - 1) {
760 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
762 /* Need to set the NULL pointer at end of array beyond the new slot. */
766 /* Allocate space and format the variable in the appropriate slot. */
767 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
768 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
772 * Reads environment variables from the given file and adds/overrides them
773 * into the environment. If the file does not exist, this does nothing.
774 * Otherwise, it must consist of empty lines, comments (line starts with '#')
775 * and assignments of the form name=value. No other forms are allowed.
778 read_environment_file(char ***env, unsigned int *envsize,
779 const char *filename)
785 f = fopen(filename, "r");
789 while (fgets(buf, sizeof(buf), f)) {
790 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
792 if (!*cp || *cp == '#' || *cp == '\n')
794 if (strchr(cp, '\n'))
795 *strchr(cp, '\n') = '\0';
796 value = strchr(cp, '=');
798 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
802 * Replace the equals sign by nul, and advance value to
807 child_set_env(env, envsize, cp, value);
814 * Sets any environment variables which have been specified by PAM
816 void do_pam_environment(char ***env, int *envsize)
818 char *equals, var_name[512], var_val[512];
822 if ((pam_env = fetch_pam_environment()) == NULL)
825 for(i = 0; pam_env[i] != NULL; i++) {
826 if ((equals = strstr(pam_env[i], "=")) == NULL)
829 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
830 memset(var_name, '\0', sizeof(var_name));
831 memset(var_val, '\0', sizeof(var_val));
833 strncpy(var_name, pam_env[i], equals - pam_env[i]);
834 strcpy(var_val, equals + 1);
836 debug("PAM environment: %s=%s", var_name, var_val);
838 child_set_env(env, envsize, var_name, var_val);
844 #if defined(HAVE_GETUSERATTR)
846 * AIX-specific login initialisation
848 void set_limit(char *user, char *soft, char *hard, int resource, int mult)
853 getrlimit(resource, &rlim);
856 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
858 rlim.rlim_cur = RLIM_INFINITY;
859 } else if (slim != 0) {
860 /* See the wackiness below */
861 if (rlim.rlim_cur == slim * mult)
864 rlim.rlim_cur = slim * mult;
869 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
871 rlim.rlim_max = RLIM_INFINITY;
872 } else if (hlim != 0) {
873 rlim.rlim_max = hlim * mult;
878 * XXX For cpu and fsize the soft limit is set to the hard limit
879 * if the hard limit is left at its default value and the soft limit
880 * is changed from its default value, either by requesting it
881 * (slim == 0) or by setting it to the current default. At least
882 * that's how rlogind does it. If you're confused you're not alone.
883 * Bug or feature? AIX 4.3.1.2
885 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
886 && hlim == 0 && slim != 0)
887 rlim.rlim_max = rlim.rlim_cur;
888 /* A specified hard limit limits the soft limit */
889 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
890 rlim.rlim_cur = rlim.rlim_max;
891 /* A soft limit can increase a hard limit */
892 else if (rlim.rlim_cur > rlim.rlim_max)
893 rlim.rlim_max = rlim.rlim_cur;
895 if (setrlimit(resource, &rlim) != 0)
896 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
899 void set_limits_from_userattr(char *user)
904 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
905 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
906 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
907 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
908 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
909 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
910 #if defined(S_UNOFILE)
911 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
914 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
915 /* Convert decimal to octal */
916 (void) snprintf(buf, sizeof(buf), "%d", mask);
917 if (sscanf(buf, "%o", &mask) == 1)
921 #endif /* defined(HAVE_GETUSERATTR) */
924 * Performs common processing for the child, such as setting up the
925 * environment, closing extra file descriptors, setting the user and group
926 * ids, and executing the command or shell.
929 do_child(const char *command, struct passwd * pw, const char *term,
930 const char *display, const char *auth_proto,
931 const char *auth_data, const char *ttyname)
933 const char *shell, *hostname = NULL, *cp = NULL;
937 unsigned int envsize, i;
939 extern char **environ;
942 #ifdef WITH_IRIX_PROJECT
944 #endif /* WITH_IRIX_PROJECT */
946 /* login(1) is only called if we execute the login shell */
947 if (options.use_login && command != NULL)
948 options.use_login = 0;
950 #ifndef USE_PAM /* pam_nologin handles this */
951 if (!options.use_login) {
952 # ifdef HAVE_LOGIN_CAP
953 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
954 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
955 _PATH_NOLOGIN), "r");
956 # else /* HAVE_LOGIN_CAP */
958 f = fopen(_PATH_NOLOGIN, "r");
959 # endif /* HAVE_LOGIN_CAP */
961 /* /etc/nologin exists. Print its contents and exit. */
962 while (fgets(buf, sizeof(buf), f))
970 /* Set login name, uid, gid, and groups. */
971 /* Login(1) does this as well, and it needs uid 0 for the "-h"
972 switch, so we let login(1) to this for us. */
973 if (!options.use_login) {
975 extern char **saved_argv;
976 extern int saved_argc;
977 char *host = get_canonical_hostname ();
979 if (sia_become_user(NULL, saved_argc, saved_argv, host,
980 pw->pw_name, ttyname, 0, NULL, NULL, SIA_BEU_SETLUID) !=
982 perror("sia_become_user");
985 if (setreuid(geteuid(), geteuid()) < 0) {
989 #else /* HAVE_OSF_SIA */
993 if (getuid() == 0 || geteuid() == 0) {
995 # ifdef HAVE_GETUSERATTR
996 set_limits_from_userattr(pw->pw_name);
997 # endif /* HAVE_GETUSERATTR */
998 # ifdef HAVE_LOGIN_CAP
999 if (setusercontext(lc, pw, pw->pw_uid,
1000 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1001 perror("unable to set user context");
1004 # else /* HAVE_LOGIN_CAP */
1005 if (setlogin(pw->pw_name) < 0)
1006 error("setlogin failed: %s", strerror(errno));
1007 if (setgid(pw->pw_gid) < 0) {
1011 /* Initialize the group list. */
1012 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1013 perror("initgroups");
1017 # ifdef WITH_IRIX_ARRAY
1018 /* initialize array session */
1019 if (newarraysess() != 0)
1020 fatal("Failed to set up new array session: %.100s",
1022 # endif /* WITH_IRIX_ARRAY */
1023 # ifdef WITH_IRIX_PROJECT
1024 /* initialize irix project info */
1025 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1026 debug("Failed to get project id, using projid 0");
1029 if (setprid(projid))
1030 fatal("Failed to initialize project %d for %s: %.100s",
1031 (int)projid, pw->pw_name, strerror(errno));
1032 # endif /* WITH_IRIX_PROJECT */
1033 /* Permanently switch to the desired uid. */
1034 permanently_set_uid(pw->pw_uid);
1035 # endif /* HAVE_LOGIN_CAP */
1037 #endif /* HAVE_OSF_SIA */
1042 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1043 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1046 * Get the shell from the password data. An empty shell field is
1047 * legal, and means /bin/sh.
1049 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1050 #ifdef HAVE_LOGIN_CAP
1051 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1055 /* Try to get AFS tokens for the local cell. */
1059 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1060 krb_afslog(cell, 0);
1066 /* Initialize the environment. */
1068 env = xmalloc(envsize * sizeof(char *));
1073 * The Windows environment contains some setting which are
1074 * important for a running system. They must not be dropped.
1078 for (ep = environ; *ep; ++ep) {
1079 char *esp = strchr(*ep, '=');
1081 child_set_env(&env, &envsize, *ep, esp + 1);
1087 if (!options.use_login) {
1088 /* Set basic environment. */
1089 child_set_env(&env, &envsize, "USER", pw->pw_name);
1090 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1091 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1092 #ifdef HAVE_LOGIN_CAP
1093 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1094 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1098 * There's no standard path on Windows. The path contains
1099 * important components pointing to the system directories,
1100 * needed for loading shared libraries. So the path better
1101 * remains intact here.
1103 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1107 snprintf(buf, sizeof buf, "%.200s/%.50s",
1108 _PATH_MAILDIR, pw->pw_name);
1109 child_set_env(&env, &envsize, "MAIL", buf);
1111 /* Normal systems set SHELL by default. */
1112 child_set_env(&env, &envsize, "SHELL", shell);
1115 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1117 /* Set custom environment options from RSA authentication. */
1118 while (custom_environment) {
1119 struct envstring *ce = custom_environment;
1122 for (i = 0; s[i] != '=' && s[i]; i++);
1125 child_set_env(&env, &envsize, s, s + i + 1);
1127 custom_environment = ce->next;
1132 snprintf(buf, sizeof buf, "%.50s %d %d",
1133 get_remote_ipaddr(), get_remote_port(), get_local_port());
1134 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1137 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
1139 child_set_env(&env, &envsize, "TERM", term);
1141 child_set_env(&env, &envsize, "DISPLAY", display);
1142 if (original_command)
1143 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1148 char *authstate,*krb5cc;
1150 if ((authstate = getenv("AUTHSTATE")) != NULL)
1151 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
1153 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
1154 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
1160 extern char *ticket;
1163 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1168 /* Pull in any environment variables that may have been set by PAM. */
1169 do_pam_environment(&env, &envsize);
1170 #endif /* USE_PAM */
1172 read_environment_file(&env,&envsize,"/etc/environment");
1175 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1176 if (auth_get_socket_name() != NULL)
1177 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1178 auth_get_socket_name());
1180 /* read $HOME/.ssh/environment. */
1181 if (!options.use_login) {
1182 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1184 read_environment_file(&env, &envsize, buf);
1187 /* dump the environment */
1188 fprintf(stderr, "Environment:\n");
1189 for (i = 0; env[i]; i++)
1190 fprintf(stderr, " %.200s\n", env[i]);
1192 /* we have to stash the hostname before we close our socket. */
1193 if (options.use_login)
1194 hostname = get_remote_name_or_ip();
1196 * Close the connection descriptors; note that this is the child, and
1197 * the server will still have the socket open, and it is important
1198 * that we do not shutdown it. Note that the descriptors cannot be
1199 * closed before building the environment, as we call
1200 * get_remote_ipaddr there.
1202 if (packet_get_connection_in() == packet_get_connection_out())
1203 close(packet_get_connection_in());
1205 close(packet_get_connection_in());
1206 close(packet_get_connection_out());
1209 * Close all descriptors related to channels. They will still remain
1210 * open in the parent.
1212 /* XXX better use close-on-exec? -markus */
1213 channel_close_all();
1216 * Close any extra file descriptors. Note that there may still be
1217 * descriptors left by system functions. They will be closed later.
1222 * Close any extra open file descriptors so that we don\'t have them
1223 * hanging around in clients. Note that we want to do this after
1224 * initgroups, because at least on Solaris 2.3 it leaves file
1227 for (i = 3; i < 64; i++)
1230 /* Change current directory to the user\'s home directory. */
1231 if (chdir(pw->pw_dir) < 0) {
1232 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1233 pw->pw_dir, strerror(errno));
1234 #ifdef HAVE_LOGIN_CAP
1235 if (login_getcapbool(lc, "requirehome", 0))
1241 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1242 * xauth are run in the proper environment.
1247 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1250 if (!options.use_login) {
1251 if (stat(SSH_USER_RC, &st) >= 0) {
1253 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_USER_RC);
1255 f = popen(_PATH_BSHELL " " SSH_USER_RC, "w");
1257 if (auth_proto != NULL && auth_data != NULL)
1258 fprintf(f, "%s %s\n", auth_proto, auth_data);
1261 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1262 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1264 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_SYSTEM_RC);
1266 f = popen(_PATH_BSHELL " " SSH_SYSTEM_RC, "w");
1268 if (auth_proto != NULL && auth_data != NULL)
1269 fprintf(f, "%s %s\n", auth_proto, auth_data);
1272 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
1273 } else if (options.xauth_location != NULL) {
1274 /* Add authority data to .Xauthority if appropriate. */
1275 if (auth_proto != NULL && auth_data != NULL) {
1276 char *screen = strchr(display, ':');
1279 "Running %.100s add %.100s %.100s %.100s\n",
1280 options.xauth_location, display,
1281 auth_proto, auth_data);
1285 "Adding %.*s/unix%s %s %s\n",
1286 (int)(screen-display), display,
1287 screen, auth_proto, auth_data);
1290 snprintf(cmd, sizeof cmd, "%s -q -",
1291 options.xauth_location);
1292 f = popen(cmd, "w");
1294 fprintf(f, "add %s %s %s\n", display,
1295 auth_proto, auth_data);
1298 fprintf(f, "add %.*s/unix%s %s %s\n",
1299 (int)(screen-display), display,
1300 screen, auth_proto, auth_data);
1304 fprintf(stderr, "Could not run %s\n",
1309 /* Get the last component of the shell name. */
1310 cp = strrchr(shell, '/');
1317 * If we have no command, execute the shell. In this case, the shell
1318 * name to be passed in argv[0] is preceded by '-' to indicate that
1319 * this is a login shell.
1322 if (!options.use_login) {
1326 * Check for mail if we have a tty and it was enabled
1327 * in server options.
1329 if (ttyname && options.check_mail) {
1331 struct stat mailstat;
1332 mailbox = getenv("MAIL");
1333 if (mailbox != NULL) {
1334 if (stat(mailbox, &mailstat) != 0 ||
1335 mailstat.st_size == 0)
1336 printf("No mail.\n");
1337 else if (mailstat.st_mtime < mailstat.st_atime)
1338 printf("You have mail.\n");
1340 printf("You have new mail.\n");
1343 /* Start the shell. Set initial character to '-'. */
1345 strncpy(buf + 1, cp, sizeof(buf) - 1);
1346 buf[sizeof(buf) - 1] = 0;
1348 /* Execute the shell. */
1351 execve(shell, argv, env);
1353 /* Executing the shell failed. */
1358 /* Launch login(1). */
1360 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1361 "-p", "-f", "--", pw->pw_name, NULL);
1363 /* Login couldn't be executed, die. */
1370 * Execute the command using the user's shell. This uses the -c
1371 * option to execute the command.
1373 argv[0] = (char *) cp;
1375 argv[2] = (char *) command;
1377 execve(shell, argv, env);
1386 static int did_init = 0;
1388 debug("session_new: init");
1389 for(i = 0; i < MAX_SESSIONS; i++) {
1390 sessions[i].used = 0;
1391 sessions[i].self = i;
1395 for(i = 0; i < MAX_SESSIONS; i++) {
1396 Session *s = &sessions[i];
1407 s->auth_data = NULL;
1408 s->auth_proto = NULL;
1411 debug("session_new: session %d", i);
1422 for(i = 0; i < MAX_SESSIONS; i++) {
1423 Session *s = &sessions[i];
1424 debug("dump: used %d session %d %p channel %d pid %d",
1434 session_open(int chanid)
1436 Session *s = session_new();
1437 debug("session_open: channel %d", chanid);
1439 error("no more sessions");
1442 s->pw = auth_get_user();
1444 fatal("no user for session %i", s->self);
1445 debug("session_open: session %d: link with channel %d", s->self, chanid);
1451 session_by_channel(int id)
1454 for(i = 0; i < MAX_SESSIONS; i++) {
1455 Session *s = &sessions[i];
1456 if (s->used && s->chanid == id) {
1457 debug("session_by_channel: session %d channel %d", i, id);
1461 debug("session_by_channel: unknown channel %d", id);
1467 session_by_pid(pid_t pid)
1470 debug("session_by_pid: pid %d", pid);
1471 for(i = 0; i < MAX_SESSIONS; i++) {
1472 Session *s = &sessions[i];
1473 if (s->used && s->pid == pid)
1476 error("session_by_pid: unknown pid %d", pid);
1482 session_window_change_req(Session *s)
1484 s->col = packet_get_int();
1485 s->row = packet_get_int();
1486 s->xpixel = packet_get_int();
1487 s->ypixel = packet_get_int();
1489 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1494 session_pty_req(Session *s)
1497 char *term_modes; /* encoded terminal modes */
1503 s->term = packet_get_string(&len);
1504 s->col = packet_get_int();
1505 s->row = packet_get_int();
1506 s->xpixel = packet_get_int();
1507 s->ypixel = packet_get_int();
1508 term_modes = packet_get_string(&len);
1511 if (strcmp(s->term, "") == 0) {
1515 /* Allocate a pty and open it. */
1516 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1521 error("session_pty_req: session %d alloc failed", s->self);
1525 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1527 * Add a cleanup function to clear the utmp entry and record logout
1528 * time in case we call fatal() (e.g., the connection gets closed).
1530 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1531 pty_setowner(s->pw, s->tty);
1532 /* Get window size from the packet. */
1533 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1535 session_proctitle(s);
1537 /* XXX parse and set terminal modes */
1543 session_subsystem_req(Session *s)
1547 char *subsys = packet_get_string(&len);
1551 log("subsystem request for %s", subsys);
1553 for (i = 0; i < options.num_subsystems; i++) {
1554 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1555 debug("subsystem: exec() %s", options.subsystem_command[i]);
1556 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1562 log("subsystem request for %s failed, subsystem not found", subsys);
1569 session_x11_req(Session *s)
1572 if (no_x11_forwarding_flag) {
1573 debug("X11 forwarding disabled in user configuration file.");
1576 if (!options.x11_forwarding) {
1577 debug("X11 forwarding disabled in server configuration file.");
1580 if (xauthfile != NULL) {
1581 debug("X11 fwd already started.");
1585 debug("Received request for X11 forwarding with auth spoofing.");
1586 if (s->display != NULL)
1587 packet_disconnect("Protocol error: X11 display already set.");
1589 s->single_connection = packet_get_char();
1590 s->auth_proto = packet_get_string(NULL);
1591 s->auth_data = packet_get_string(NULL);
1592 s->screen = packet_get_int();
1595 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1596 if (s->display == NULL) {
1597 xfree(s->auth_proto);
1598 xfree(s->auth_data);
1601 xauthfile = xmalloc(MAXPATHLEN);
1602 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1603 temporarily_use_uid(s->pw->pw_uid);
1604 if (mkdtemp(xauthfile) == NULL) {
1606 error("private X11 dir: mkdtemp %s failed: %s",
1607 xauthfile, strerror(errno));
1610 xfree(s->auth_proto);
1611 xfree(s->auth_data);
1612 /* XXXX remove listening channels */
1615 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1616 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1620 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1625 session_shell_req(Session *s)
1627 /* if forced_command == NULL, the shell is execed */
1628 char *shell = forced_command;
1632 do_exec_no_pty(s, shell, s->pw);
1634 do_exec_pty(s, shell, s->pw);
1639 session_exec_req(Session *s)
1642 char *command = packet_get_string(&len);
1644 if (forced_command) {
1645 original_command = command;
1646 command = forced_command;
1647 debug("Forced command '%.500s'", forced_command);
1651 do_exec_no_pty(s, command, s->pw);
1653 do_exec_pty(s, command, s->pw);
1654 if (forced_command == NULL)
1660 session_input_channel_req(int id, void *arg)
1669 rtype = packet_get_string(&len);
1670 reply = packet_get_char();
1672 s = session_by_channel(id);
1674 fatal("session_input_channel_req: channel %d: no session", id);
1675 c = channel_lookup(id);
1677 fatal("session_input_channel_req: channel %d: bad channel", id);
1679 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1680 s->self, id, rtype, reply);
1683 * a session is in LARVAL state until a shell
1684 * or programm is executed
1686 if (c->type == SSH_CHANNEL_LARVAL) {
1687 if (strcmp(rtype, "shell") == 0) {
1688 success = session_shell_req(s);
1689 } else if (strcmp(rtype, "exec") == 0) {
1690 success = session_exec_req(s);
1691 } else if (strcmp(rtype, "pty-req") == 0) {
1692 success = session_pty_req(s);
1693 } else if (strcmp(rtype, "x11-req") == 0) {
1694 success = session_x11_req(s);
1695 } else if (strcmp(rtype, "subsystem") == 0) {
1696 success = session_subsystem_req(s);
1699 if (strcmp(rtype, "window-change") == 0) {
1700 success = session_window_change_req(s);
1704 packet_start(success ?
1705 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1706 packet_put_int(c->remote_id);
1713 session_set_fds(Session *s, int fdin, int fdout, int fderr)
1716 fatal("session_set_fds: called for proto != 2.0");
1718 * now that have a child and a pipe to the child,
1719 * we can activate our channel and register the fd's
1721 if (s->chanid == -1)
1722 fatal("no channel for session %d", s->self);
1723 channel_set_fds(s->chanid,
1725 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1729 session_pty_cleanup(Session *s)
1731 if (s == NULL || s->ttyfd == -1)
1734 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1736 /* Cancel the cleanup function. */
1737 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1739 /* Record that the user has logged out. */
1740 record_logout(s->pid, s->tty);
1742 /* Release the pseudo-tty. */
1743 pty_release(s->tty);
1746 * Close the server side of the socket pairs. We must do this after
1747 * the pty cleanup, so that another process doesn't get this pty
1748 * while we're still cleaning up.
1750 if (close(s->ptymaster) < 0)
1751 error("close(s->ptymaster): %s", strerror(errno));
1755 session_exit_message(Session *s, int status)
1759 fatal("session_close: no session");
1760 c = channel_lookup(s->chanid);
1762 fatal("session_close: session %d: no channel %d",
1763 s->self, s->chanid);
1764 debug("session_exit_message: session %d channel %d pid %d",
1765 s->self, s->chanid, s->pid);
1767 if (WIFEXITED(status)) {
1768 channel_request_start(s->chanid,
1770 packet_put_int(WEXITSTATUS(status));
1772 } else if (WIFSIGNALED(status)) {
1773 channel_request_start(s->chanid,
1775 packet_put_int(WTERMSIG(status));
1777 packet_put_char(WCOREDUMP(status));
1778 #else /* WCOREDUMP */
1780 #endif /* WCOREDUMP */
1781 packet_put_cstring("");
1782 packet_put_cstring("");
1785 /* Some weird exit cause. Just exit. */
1786 packet_disconnect("wait returned status %04x.", status);
1789 /* disconnect channel */
1790 debug("session_exit_message: release channel %d", s->chanid);
1791 channel_cancel_cleanup(s->chanid);
1793 * emulate a write failure with 'chan_write_failed', nobody will be
1794 * interested in data we write.
1795 * Note that we must not call 'chan_read_failed', since there could
1796 * be some more data waiting in the pipe.
1798 if (c->ostate != CHAN_OUTPUT_CLOSED)
1799 chan_write_failed(c);
1804 session_free(Session *s)
1806 debug("session_free: session %d pid %d", s->self, s->pid);
1812 xfree(s->auth_data);
1814 xfree(s->auth_proto);
1819 session_close(Session *s)
1821 session_pty_cleanup(s);
1823 session_proctitle(s);
1827 session_close_by_pid(pid_t pid, int status)
1829 Session *s = session_by_pid(pid);
1831 debug("session_close_by_pid: no session for pid %d", s->pid);
1834 if (s->chanid != -1)
1835 session_exit_message(s, status);
1840 * this is called when a channel dies before
1841 * the session 'child' itself dies
1844 session_close_by_channel(int id, void *arg)
1846 Session *s = session_by_channel(id);
1848 debug("session_close_by_channel: no session for channel %d", id);
1851 /* disconnect channel */
1852 channel_cancel_cleanup(s->chanid);
1855 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1857 /* close session immediately */
1860 /* notify child, delay session cleanup */
1862 fatal("session_close_by_channel: Unsafe s->pid = %d", s->pid);
1863 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1864 error("session_close_by_channel: kill %d: %s",
1865 s->pid, strerror(errno));
1870 session_tty_list(void)
1872 static char buf[1024];
1875 for(i = 0; i < MAX_SESSIONS; i++) {
1876 Session *s = &sessions[i];
1877 if (s->used && s->ttyfd != -1) {
1879 strlcat(buf, ",", sizeof buf);
1880 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1884 strlcpy(buf, "notty", sizeof buf);
1889 session_proctitle(Session *s)
1892 error("no user for session %d", s->self);
1894 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1898 do_authenticated2(void)
1900 #ifdef HAVE_LOGIN_CAP
1905 * Cancel the alarm we set to limit the time taken for
1909 if (startup_pipe != -1) {
1910 close(startup_pipe);
1913 #ifdef HAVE_LOGIN_CAP
1914 pw = auth_get_user();
1915 if ((lc = login_getclass(pw->pw_class)) == NULL) {
1916 error("unable to get login class");
1922 xauthfile_cleanup_proc(NULL);