2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * Created: Fri Mar 17 17:09:28 1995 ylo
6 * This program is the ssh daemon. It listens for connections from clients, and
7 * performs authentication, executes use commands or shell, and forwards
8 * information to/from the application to the user client over an encrypted
9 * connection. This can also handle forwarding of X11, TCP/IP, and authentication
31 int allow_severity = LOG_INFO;
32 int deny_severity = LOG_WARNING;
39 /* Local Xauthority file. */
40 static char *xauthfile = NULL;
42 /* Server configuration options. */
43 ServerOptions options;
45 /* Name of the server configuration file. */
46 char *config_file_name = SERVER_CONFIG_FILE;
49 * Flag indicating whether IPv4 or IPv6. This can be set on the command line.
50 * Default value is AF_UNSPEC means both IPv4 and IPv6.
52 int IPv4or6 = AF_UNSPEC;
55 * Debug mode flag. This can be set on the command line. If debug
56 * mode is enabled, extra debugging output will be sent to the system
57 * log, the daemon will not go to background, and will exit after processing
58 * the first connection.
62 /* Flag indicating that the daemon is being started from inetd. */
65 /* debug goes to stderr unless inetd_flag is set */
68 /* argv[0] without path. */
71 /* Saved arguments to main(). */
75 * The sockets that the server is listening; this is used in the SIGHUP
78 #define MAX_LISTEN_SOCKS 16
79 int listen_socks[MAX_LISTEN_SOCKS];
80 int num_listen_socks = 0;
83 * the client's version string, passed by sshd2 in compat mode. if != NULL,
84 * sshd will skip the version-number exchange
86 char *client_version_string = NULL;
88 /* Flags set in auth-rsa from authorized_keys flags. These are set in auth-rsa.c. */
89 int no_port_forwarding_flag = 0;
90 int no_agent_forwarding_flag = 0;
91 int no_x11_forwarding_flag = 0;
94 /* RSA authentication "command=" option. */
95 char *forced_command = NULL;
97 /* RSA authentication "environment=" options. */
98 struct envstring *custom_environment = NULL;
100 /* Session id for the current session. */
101 unsigned char session_id[16];
104 * Any really sensitive data in the application is contained in this
105 * structure. The idea is that this structure could be locked into memory so
106 * that the pages do not get written into swap. However, there are some
107 * problems. The private key contains BIGNUMs, and we do not (in principle)
108 * have access to the internals of them, and locking just the structure is
109 * not very useful. Currently, memory locking is not implemented.
112 RSA *private_key; /* Private part of server key. */
113 RSA *host_key; /* Private part of host key. */
117 * Flag indicating whether the current session key has been used. This flag
118 * is set whenever the key is used, and cleared when the key is regenerated.
122 /* This is set to true when SIGHUP is received. */
123 int received_sighup = 0;
125 /* Public side of the server key. This value is regenerated regularly with
129 /* Prototypes for various functions defined later in this file. */
130 void do_connection();
131 void do_authentication(char *user);
132 void do_authloop(struct passwd * pw);
133 void do_fake_authloop(char *user);
134 void do_authenticated(struct passwd * pw);
135 void do_exec_pty(const char *command, int ptyfd, int ttyfd,
136 const char *ttyname, struct passwd * pw, const char *term,
137 const char *display, const char *auth_proto,
138 const char *auth_data);
139 void do_exec_no_pty(const char *command, struct passwd * pw,
140 const char *display, const char *auth_proto,
141 const char *auth_data);
142 void do_child(const char *command, struct passwd * pw, const char *term,
143 const char *display, const char *auth_proto,
144 const char *auth_data, const char *ttyname);
147 * Close all listening sockets
150 close_listen_socks(void)
153 for (i = 0; i < num_listen_socks; i++)
154 close(listen_socks[i]);
155 num_listen_socks = -1;
159 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
160 * the effect is to reread the configuration file (and to regenerate
164 sighup_handler(int sig)
167 signal(SIGHUP, sighup_handler);
171 * Called from the main program after receiving SIGHUP.
172 * Restarts the server.
177 log("Received SIGHUP; restarting.");
178 close_listen_socks();
179 execv(saved_argv[0], saved_argv);
180 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
185 * Generic signal handler for terminating signals in the master daemon.
186 * These close the listen socket; not closing it seems to cause "Address
187 * already in use" problems on some machines, which is inconvenient.
190 sigterm_handler(int sig)
192 log("Received signal %d; terminating.", sig);
193 close_listen_socks();
198 * SIGCHLD handler. This is called whenever a child dies. This will then
199 * reap any zombies left by exited c.
202 main_sigchld_handler(int sig)
204 int save_errno = errno;
207 while (waitpid(-1, &status, WNOHANG) > 0)
210 signal(SIGCHLD, main_sigchld_handler);
215 * Signal handler for the alarm after the login grace period has expired.
218 grace_alarm_handler(int sig)
220 /* Close the connection. */
223 /* Log error and exit. */
224 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
228 * convert ssh auth msg type into description
231 get_authname(int type)
234 case SSH_CMSG_AUTH_PASSWORD:
236 case SSH_CMSG_AUTH_RSA:
238 case SSH_CMSG_AUTH_RHOSTS_RSA:
240 case SSH_CMSG_AUTH_RHOSTS:
243 case SSH_CMSG_AUTH_KERBEROS:
247 case SSH_CMSG_AUTH_TIS_RESPONSE:
251 fatal("get_authname: unknown auth %d: internal error", type);
256 * Signal handler for the key regeneration alarm. Note that this
257 * alarm only occurs in the daemon waiting for connections, and it does not
258 * do anything with the private key or random state before forking.
259 * Thus there should be no concurrency control/asynchronous execution
263 key_regeneration_alarm(int sig)
265 int save_errno = errno;
267 /* Check if we should generate a new key. */
269 /* This should really be done in the background. */
270 log("Generating new %d bit RSA key.", options.server_key_bits);
272 if (sensitive_data.private_key != NULL)
273 RSA_free(sensitive_data.private_key);
274 sensitive_data.private_key = RSA_new();
276 if (public_key != NULL)
277 RSA_free(public_key);
278 public_key = RSA_new();
280 rsa_generate_key(sensitive_data.private_key, public_key,
281 options.server_key_bits);
284 log("RSA key generation complete.");
286 /* Reschedule the alarm. */
287 signal(SIGALRM, key_regeneration_alarm);
288 alarm(options.key_regeneration_time);
293 * Main program for the daemon.
296 main(int ac, char **av)
300 int opt, sock_in = 0, sock_out = 0, newsock, i, fdsetsz, pid, on = 1;
302 int remote_major, remote_minor;
305 struct sockaddr_storage from;
306 char buf[100]; /* Must not be larger than remote_version. */
307 char remote_version[100]; /* Must be at least as big as buf. */
308 const char *remote_ip;
312 struct linger linger;
314 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
315 int listen_sock, maxfd;
319 if (strchr(av[0], '/'))
320 av0 = strrchr(av[0], '/') + 1;
324 /* Initialize configuration options to their default values. */
325 initialize_server_options(&options);
327 /* Parse command-line arguments. */
328 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ46")) != EOF) {
337 config_file_name = optarg;
341 options.log_level = SYSLOG_LEVEL_DEBUG;
350 options.log_level = SYSLOG_LEVEL_QUIET;
353 options.server_key_bits = atoi(optarg);
356 options.ports_from_cmdline = 1;
357 if (options.num_ports >= MAX_PORTS)
358 fatal("too many ports.\n");
359 options.ports[options.num_ports++] = atoi(optarg);
362 options.login_grace_time = atoi(optarg);
365 options.key_regeneration_time = atoi(optarg);
368 options.host_key_file = optarg;
371 client_version_string = optarg;
372 /* only makes sense with inetd_flag, i.e. no listen() */
377 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
379 fprintf(stderr, "Compiled with RSAref.\n");
381 fprintf(stderr, "Usage: %s [options]\n", av0);
382 fprintf(stderr, "Options:\n");
383 fprintf(stderr, " -f file Configuration file (default %s)\n", SERVER_CONFIG_FILE);
384 fprintf(stderr, " -d Debugging mode\n");
385 fprintf(stderr, " -i Started from inetd\n");
386 fprintf(stderr, " -q Quiet (no logging)\n");
387 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
388 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
389 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
390 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
391 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
393 fprintf(stderr, " -4 Use IPv4 only\n");
394 fprintf(stderr, " -6 Use IPv6 only\n");
400 * Force logging to stderr until we have loaded the private host
401 * key (unless started from inetd)
404 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
405 options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility,
408 /* check if RSA support exists */
409 if (rsa_alive() == 0) {
411 printf("sshd: no RSA support in libssl and libcrypto -- exiting. See ssl(8)\n");
412 log("no RSA support in libssl and libcrypto -- exiting. See ssl(8)");
415 /* Read server configuration options from the configuration file. */
416 read_server_config(&options, config_file_name);
418 /* Fill in default values for those options not explicitly set. */
419 fill_default_server_options(&options);
421 /* Check certain values for sanity. */
422 if (options.server_key_bits < 512 ||
423 options.server_key_bits > 32768) {
424 fprintf(stderr, "Bad server key size.\n");
427 /* Check that there are no remaining arguments. */
429 fprintf(stderr, "Extra argument %s.\n", av[optind]);
433 debug("sshd version %.100s", SSH_VERSION);
435 sensitive_data.host_key = RSA_new();
437 /* Load the host key. It must have empty passphrase. */
438 if (!load_private_key(options.host_key_file, "",
439 sensitive_data.host_key, &comment)) {
440 error("Could not load host key: %.200s: %.100s",
441 options.host_key_file, strerror(errno));
446 /* Initialize the log (it is reinitialized below in case we
448 if (debug_flag && !inetd_flag)
450 log_init(av0, options.log_level, options.log_facility, log_stderr);
452 /* If not in debugging mode, and not started from inetd,
453 disconnect from the controlling terminal, and fork. The
454 original process exits. */
455 if (!debug_flag && !inetd_flag) {
458 #endif /* TIOCNOTTY */
459 if (daemon(0, 0) < 0)
460 fatal("daemon() failed: %.200s", strerror(errno));
462 /* Disconnect from the controlling tty. */
464 fd = open("/dev/tty", O_RDWR | O_NOCTTY);
466 (void) ioctl(fd, TIOCNOTTY, NULL);
469 #endif /* TIOCNOTTY */
471 /* Reinitialize the log (because of the fork above). */
472 log_init(av0, options.log_level, options.log_facility, log_stderr);
474 /* Check that server and host key lengths differ sufficiently.
475 This is necessary to make double encryption work with rsaref.
476 Oh, I hate software patents. I dont know if this can go? Niels */
477 if (options.server_key_bits >
478 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
479 options.server_key_bits <
480 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
481 options.server_key_bits =
482 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
483 debug("Forcing server key to %d bits to make it differ from host key.",
484 options.server_key_bits);
486 /* Do not display messages to stdout in RSA code. */
489 /* Initialize the random number generator. */
492 /* Chdir to the root directory so that the current disk can be
493 unmounted if desired. */
496 /* Close connection cleanly after attack. */
497 cipher_attack_detected = packet_disconnect;
499 /* Start listening for a socket, unless started from inetd. */
502 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
506 /* We intentionally do not close the descriptors 0, 1, and 2
507 as our code for setting the descriptors won\'t work
508 if ttyfd happens to be one of those. */
509 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
511 public_key = RSA_new();
512 sensitive_data.private_key = RSA_new();
514 log("Generating %d bit RSA key.", options.server_key_bits);
515 rsa_generate_key(sensitive_data.private_key, public_key,
516 options.server_key_bits);
518 log("RSA key generation complete.");
520 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
521 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
523 if (num_listen_socks >= MAX_LISTEN_SOCKS)
524 fatal("Too many listen sockets. "
525 "Enlarge MAX_LISTEN_SOCKS");
526 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
527 ntop, sizeof(ntop), strport, sizeof(strport),
528 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
529 error("getnameinfo failed");
532 /* Create socket for listening. */
533 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
534 if (listen_sock < 0) {
535 /* kernel may not support ipv6 */
536 verbose("socket: %.100s", strerror(errno));
539 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
540 error("listen_sock O_NONBLOCK: %s", strerror(errno));
545 * Set socket options. We try to make the port
546 * reusable and have it close as fast as possible
547 * without waiting in unnecessary wait states on
550 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
551 (void *) &on, sizeof(on));
554 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
555 (void *) &linger, sizeof(linger));
557 debug("Bind to port %s on %s.", strport, ntop);
559 /* Bind the socket to the desired port. */
560 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
561 error("Bind to port %s on %s failed: %.200s.",
562 strport, ntop, strerror(errno));
566 listen_socks[num_listen_socks] = listen_sock;
569 /* Start listening on the port. */
570 log("Server listening on %s port %s.", ntop, strport);
571 if (listen(listen_sock, 5) < 0)
572 fatal("listen: %.100s", strerror(errno));
575 freeaddrinfo(options.listen_addrs);
577 if (!num_listen_socks)
578 fatal("Cannot bind any address.");
582 * Record our pid in /etc/sshd_pid to make it easier
583 * to kill the correct sshd. We don\'t want to do
584 * this before the bind above because the bind will
585 * fail if there already is a daemon, and this will
586 * overwrite any old pid in the file.
588 f = fopen(SSH_DAEMON_PID_FILE, "w");
590 fprintf(f, "%u\n", (unsigned int) getpid());
595 public_key = RSA_new();
596 sensitive_data.private_key = RSA_new();
598 log("Generating %d bit RSA key.", options.server_key_bits);
599 rsa_generate_key(sensitive_data.private_key, public_key,
600 options.server_key_bits);
602 log("RSA key generation complete.");
604 /* Schedule server key regeneration alarm. */
605 signal(SIGALRM, key_regeneration_alarm);
606 alarm(options.key_regeneration_time);
608 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
609 signal(SIGHUP, sighup_handler);
610 signal(SIGTERM, sigterm_handler);
611 signal(SIGQUIT, sigterm_handler);
613 /* Arrange SIGCHLD to be caught. */
614 signal(SIGCHLD, main_sigchld_handler);
616 /* setup fd set for listen */
618 for (i = 0; i < num_listen_socks; i++)
619 if (listen_socks[i] > maxfd)
620 maxfd = listen_socks[i];
621 fdsetsz = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
622 fdset = (fd_set *)xmalloc(fdsetsz);
625 * Stay listening for connections until the system crashes or
626 * the daemon is killed with a signal.
631 /* Wait in select until there is a connection. */
632 memset(fdset, 0, fdsetsz);
633 for (i = 0; i < num_listen_socks; i++)
634 FD_SET(listen_socks[i], fdset);
635 if (select(maxfd + 1, fdset, NULL, NULL, NULL) < 0) {
637 error("select: %.100s", strerror(errno));
640 for (i = 0; i < num_listen_socks; i++) {
641 if (!FD_ISSET(listen_socks[i], fdset))
643 fromlen = sizeof(from);
644 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
647 if (errno != EINTR && errno != EWOULDBLOCK)
648 error("accept: %.100s", strerror(errno));
651 if (fcntl(newsock, F_SETFL, 0) < 0) {
652 error("newsock del O_NONBLOCK: %s", strerror(errno));
656 * Got connection. Fork a child to handle it, unless
657 * we are in debugging mode.
661 * In debugging mode. Close the listening
662 * socket, and start processing the
663 * connection without forking.
665 debug("Server will not fork when running in debugging mode.");
666 close_listen_socks();
673 * Normal production daemon. Fork, and have
674 * the child process the connection. The
675 * parent continues listening.
677 if ((pid = fork()) == 0) {
679 * Child. Close the listening socket, and start using the
680 * accepted socket. Reinitialize logging (since our pid has
681 * changed). We break out of the loop to handle the connection.
683 close_listen_socks();
686 log_init(av0, options.log_level, options.log_facility, log_stderr);
691 /* Parent. Stay in the loop. */
693 error("fork: %.100s", strerror(errno));
695 debug("Forked child %d.", pid);
697 /* Mark that the key has been used (it was "given" to the child). */
702 /* Close the new socket (the child is now taking care of it). */
704 } /* for (i = 0; i < num_listen_socks; i++) */
705 /* child process check (or debug mode) */
706 if (num_listen_socks < 0)
711 /* This is the child processing a new connection. */
714 * Disable the key regeneration alarm. We will not regenerate the
715 * key since we are no longer in a position to give it to anyone. We
716 * will not restart on SIGHUP since it no longer makes sense.
719 signal(SIGALRM, SIG_DFL);
720 signal(SIGHUP, SIG_DFL);
721 signal(SIGTERM, SIG_DFL);
722 signal(SIGQUIT, SIG_DFL);
723 signal(SIGCHLD, SIG_DFL);
726 * Set socket options for the connection. We want the socket to
727 * close as fast as possible without waiting for anything. If the
728 * connection is not a socket, these will do nothing.
730 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
733 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
736 * Register our connection. This turns encryption off because we do
739 packet_set_connection(sock_in, sock_out);
741 remote_port = get_remote_port();
742 remote_ip = get_remote_ipaddr();
744 /* Check whether logins are denied from this host. */
746 /* XXX LIBWRAP noes not know about IPv6 */
748 struct request_info req;
750 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
753 if (!hosts_access(&req)) {
758 /*XXX IPv6 verbose("Connection from %.500s port %d", eval_client(&req), remote_port); */
761 /* Log the connection. */
762 verbose("Connection from %.500s port %d", remote_ip, remote_port);
765 * We don\'t want to listen forever unless the other side
766 * successfully authenticates itself. So we set up an alarm which is
767 * cleared after successful authentication. A limit of zero
768 * indicates no limit. Note that we don\'t set the alarm in debugging
769 * mode; it is just annoying to have the server exit just when you
770 * are about to discover the bug.
772 signal(SIGALRM, grace_alarm_handler);
774 alarm(options.login_grace_time);
776 if (client_version_string != NULL) {
777 /* we are exec'ed by sshd2, so skip exchange of protocol version */
778 strlcpy(buf, client_version_string, sizeof(buf));
780 /* Send our protocol version identification. */
781 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
782 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
783 if (atomicio(write, sock_out, buf, strlen(buf)) != strlen(buf))
784 fatal("Could not write ident string to %s.", remote_ip);
786 /* Read other side\'s version identification. */
787 for (i = 0; i < sizeof(buf) - 1; i++) {
788 if (read(sock_in, &buf[i], 1) != 1)
789 fatal("Did not receive ident string from %s.", remote_ip);
790 if (buf[i] == '\r') {
795 if (buf[i] == '\n') {
801 buf[sizeof(buf) - 1] = 0;
805 * Check that the versions match. In future this might accept
806 * several versions and set appropriate flags to handle them.
808 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
809 remote_version) != 3) {
810 char *s = "Protocol mismatch.\n";
812 (void) atomicio(write, sock_out, s, strlen(s));
815 fatal("Bad protocol version identification '%.100s' from %s",
818 debug("Client protocol version %d.%d; client software version %.100s",
819 remote_major, remote_minor, remote_version);
820 if (remote_major != PROTOCOL_MAJOR) {
821 char *s = "Protocol major versions differ.\n";
823 (void) atomicio(write, sock_out, s, strlen(s));
826 fatal("Protocol major versions differ for %s: %d vs. %d",
827 remote_ip, PROTOCOL_MAJOR, remote_major);
829 /* Check that the client has sufficiently high software version. */
830 if (remote_major == 1 && remote_minor < 3)
831 packet_disconnect("Your ssh version is too old and is no longer supported. Please install a newer version.");
833 if (remote_major == 1 && remote_minor == 3) {
835 if (strcmp(remote_version, "OpenSSH-1.1") != 0) {
836 debug("Agent forwarding disabled, remote version is not compatible.");
837 no_agent_forwarding_flag = 1;
841 * Check that the connection comes from a privileged port. Rhosts-
842 * and Rhosts-RSA-Authentication only make sense from priviledged
843 * programs. Of course, if the intruder has root access on his local
844 * machine, he can connect from any port. So do not use these
845 * authentication methods from machines that you do not trust.
847 if (remote_port >= IPPORT_RESERVED ||
848 remote_port < IPPORT_RESERVED / 2) {
849 options.rhosts_authentication = 0;
850 options.rhosts_rsa_authentication = 0;
853 if (!packet_connection_is_ipv4() &&
854 options.kerberos_authentication) {
855 debug("Kerberos Authentication disabled, only available for IPv4.");
856 options.kerberos_authentication = 0;
860 packet_set_nonblocking();
862 /* Handle the connection. */
866 /* Cleanup user's ticket cache file. */
867 if (options.kerberos_ticket_cleanup)
871 /* Cleanup user's local Xauthority file. */
875 /* The connection has been terminated. */
876 verbose("Closing connection to %.100s", remote_ip);
887 * Process an incoming connection. Protocol version identifiers have already
888 * been exchanged. This sends server key and performs the key exchange.
889 * Server and host keys will no longer be needed after this functions.
895 BIGNUM *session_key_int;
896 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
897 unsigned char check_bytes[8];
899 unsigned int cipher_type, auth_mask, protocol_flags;
900 int plen, slen, ulen;
904 * Generate check bytes that the client must send back in the user
905 * packet in order for it to be accepted; this is used to defy ip
906 * spoofing attacks. Note that this only works against somebody
907 * doing IP spoofing from a remote machine; any machine on the local
908 * network can still see outgoing packets and catch the random
909 * cookie. This only affects rhosts authentication, and this is one
910 * of the reasons why it is inherently insecure.
912 for (i = 0; i < 8; i++) {
915 check_bytes[i] = rand & 0xff;
920 * Send our public key. We include in the packet 64 bits of random
921 * data that must be matched in the reply in order to prevent IP
924 packet_start(SSH_SMSG_PUBLIC_KEY);
925 for (i = 0; i < 8; i++)
926 packet_put_char(check_bytes[i]);
928 /* Store our public server RSA key. */
929 packet_put_int(BN_num_bits(public_key->n));
930 packet_put_bignum(public_key->e);
931 packet_put_bignum(public_key->n);
933 /* Store our public host RSA key. */
934 packet_put_int(BN_num_bits(sensitive_data.host_key->n));
935 packet_put_bignum(sensitive_data.host_key->e);
936 packet_put_bignum(sensitive_data.host_key->n);
938 /* Put protocol flags. */
939 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
941 /* Declare which ciphers we support. */
942 packet_put_int(cipher_mask());
944 /* Declare supported authentication types. */
946 if (options.rhosts_authentication)
947 auth_mask |= 1 << SSH_AUTH_RHOSTS;
948 if (options.rhosts_rsa_authentication)
949 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
950 if (options.rsa_authentication)
951 auth_mask |= 1 << SSH_AUTH_RSA;
953 if (options.kerberos_authentication)
954 auth_mask |= 1 << SSH_AUTH_KERBEROS;
957 if (options.kerberos_tgt_passing)
958 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
959 if (options.afs_token_passing)
960 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
963 if (options.skey_authentication == 1)
964 auth_mask |= 1 << SSH_AUTH_TIS;
966 if (options.password_authentication)
967 auth_mask |= 1 << SSH_AUTH_PASSWORD;
968 packet_put_int(auth_mask);
970 /* Send the packet and wait for it to be sent. */
974 debug("Sent %d bit public key and %d bit host key.",
975 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
977 /* Read clients reply (cipher type and session key). */
978 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
980 /* Get cipher type and check whether we accept this. */
981 cipher_type = packet_get_char();
983 if (!(cipher_mask() & (1 << cipher_type)))
984 packet_disconnect("Warning: client selects unsupported cipher.");
986 /* Get check bytes from the packet. These must match those we
987 sent earlier with the public key packet. */
988 for (i = 0; i < 8; i++)
989 if (check_bytes[i] != packet_get_char())
990 packet_disconnect("IP Spoofing check bytes do not match.");
992 debug("Encryption type: %.200s", cipher_name(cipher_type));
994 /* Get the encrypted integer. */
995 session_key_int = BN_new();
996 packet_get_bignum(session_key_int, &slen);
998 protocol_flags = packet_get_int();
999 packet_set_protocol_flags(protocol_flags);
1001 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
1004 * Decrypt it using our private server key and private host key (key
1005 * with larger modulus first).
1007 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
1008 /* Private key has bigger modulus. */
1009 if (BN_num_bits(sensitive_data.private_key->n) <
1010 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1011 fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1012 get_remote_ipaddr(),
1013 BN_num_bits(sensitive_data.private_key->n),
1014 BN_num_bits(sensitive_data.host_key->n),
1015 SSH_KEY_BITS_RESERVED);
1017 rsa_private_decrypt(session_key_int, session_key_int,
1018 sensitive_data.private_key);
1019 rsa_private_decrypt(session_key_int, session_key_int,
1020 sensitive_data.host_key);
1022 /* Host key has bigger modulus (or they are equal). */
1023 if (BN_num_bits(sensitive_data.host_key->n) <
1024 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1025 fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1026 get_remote_ipaddr(),
1027 BN_num_bits(sensitive_data.host_key->n),
1028 BN_num_bits(sensitive_data.private_key->n),
1029 SSH_KEY_BITS_RESERVED);
1031 rsa_private_decrypt(session_key_int, session_key_int,
1032 sensitive_data.host_key);
1033 rsa_private_decrypt(session_key_int, session_key_int,
1034 sensitive_data.private_key);
1037 compute_session_id(session_id, check_bytes,
1038 sensitive_data.host_key->n,
1039 sensitive_data.private_key->n);
1042 * Extract session key from the decrypted integer. The key is in the
1043 * least significant 256 bits of the integer; the first byte of the
1044 * key is in the highest bits.
1046 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1047 len = BN_num_bytes(session_key_int);
1048 if (len < 0 || len > sizeof(session_key))
1049 fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
1050 get_remote_ipaddr(),
1051 len, sizeof(session_key));
1052 memset(session_key, 0, sizeof(session_key));
1053 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
1055 /* Xor the first 16 bytes of the session key with the session id. */
1056 for (i = 0; i < 16; i++)
1057 session_key[i] ^= session_id[i];
1059 /* Destroy the decrypted integer. It is no longer needed. */
1060 BN_clear_free(session_key_int);
1062 /* Set the session key. From this on all communications will be encrypted. */
1063 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1065 /* Destroy our copy of the session key. It is no longer needed. */
1066 memset(session_key, 0, sizeof(session_key));
1068 debug("Received session key; encryption turned on.");
1070 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1071 packet_start(SSH_SMSG_SUCCESS);
1073 packet_write_wait();
1075 /* Get the name of the user that we wish to log in as. */
1076 packet_read_expect(&plen, SSH_CMSG_USER);
1078 /* Get the user name. */
1079 user = packet_get_string(&ulen);
1080 packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER);
1082 /* Destroy the private and public keys. They will no longer be needed. */
1083 RSA_free(public_key);
1084 RSA_free(sensitive_data.private_key);
1085 RSA_free(sensitive_data.host_key);
1087 setproctitle("%s", user);
1088 /* Do the authentication. */
1089 do_authentication(user);
1093 * Check if the user is allowed to log in via ssh. If user is listed in
1094 * DenyUsers or user's primary group is listed in DenyGroups, false will
1095 * be returned. If AllowUsers isn't empty and user isn't listed there, or
1096 * if AllowGroups isn't empty and user isn't listed there, false will be
1097 * returned. Otherwise true is returned.
1098 * XXX This function should also check if user has a valid shell
1101 allowed_user(struct passwd * pw)
1106 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
1110 /* XXX Should check for valid login shell */
1112 /* Return false if user is listed in DenyUsers */
1113 if (options.num_deny_users > 0) {
1116 for (i = 0; i < options.num_deny_users; i++)
1117 if (match_pattern(pw->pw_name, options.deny_users[i]))
1120 /* Return false if AllowUsers isn't empty and user isn't listed there */
1121 if (options.num_allow_users > 0) {
1124 for (i = 0; i < options.num_allow_users; i++)
1125 if (match_pattern(pw->pw_name, options.allow_users[i]))
1127 /* i < options.num_allow_users iff we break for loop */
1128 if (i >= options.num_allow_users)
1131 /* Get the primary group name if we need it. Return false if it fails */
1132 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
1133 grp = getgrgid(pw->pw_gid);
1137 /* Return false if user's group is listed in DenyGroups */
1138 if (options.num_deny_groups > 0) {
1141 for (i = 0; i < options.num_deny_groups; i++)
1142 if (match_pattern(grp->gr_name, options.deny_groups[i]))
1146 * Return false if AllowGroups isn't empty and user's group
1147 * isn't listed there
1149 if (options.num_allow_groups > 0) {
1152 for (i = 0; i < options.num_allow_groups; i++)
1153 if (match_pattern(grp->gr_name, options.allow_groups[i]))
1155 /* i < options.num_allow_groups iff we break for
1157 if (i >= options.num_allow_groups)
1161 /* We found no reason not to let this user try to log on... */
1166 * Performs authentication of an incoming connection. Session key has already
1167 * been exchanged and encryption is enabled. User is the user name to log
1168 * in as (received from the client).
1171 do_authentication(char *user)
1173 struct passwd *pw, pwcopy;
1176 /* If machine has AFS, set process authentication group. */
1183 /* Verify that the user is a valid user. */
1184 pw = getpwnam(user);
1185 if (!pw || !allowed_user(pw))
1186 do_fake_authloop(user);
1188 /* Take a copy of the returned structure. */
1189 memset(&pwcopy, 0, sizeof(pwcopy));
1190 pwcopy.pw_name = xstrdup(pw->pw_name);
1191 pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
1192 pwcopy.pw_uid = pw->pw_uid;
1193 pwcopy.pw_gid = pw->pw_gid;
1194 pwcopy.pw_dir = xstrdup(pw->pw_dir);
1195 pwcopy.pw_shell = xstrdup(pw->pw_shell);
1203 * If we are not running as root, the user must have the same uid as
1206 if (getuid() != 0 && pw->pw_uid != getuid())
1207 packet_disconnect("Cannot change user when server not running as root.");
1209 debug("Attempting authentication for %.100s.", user);
1211 /* If the user has no password, accept authentication immediately. */
1212 if (options.password_authentication &&
1214 (!options.kerberos_authentication || options.kerberos_or_local_passwd) &&
1217 auth_pam_password(pw, "")) {
1219 auth_password(pw, "")) {
1220 #endif /* USE_PAM */
1221 /* Authentication with empty password succeeded. */
1222 log("Login for user %s from %.100s, accepted without authentication.",
1223 pw->pw_name, get_remote_ipaddr());
1225 /* Loop until the user has been authenticated or the
1226 connection is closed, do_authloop() returns only if
1227 authentication is successfull */
1231 /* Check if the user is logging in as root and root logins are disallowed. */
1232 if (pw->pw_uid == 0 && !options.permit_root_login) {
1234 log("Root login accepted for forced command.");
1236 packet_disconnect("ROOT LOGIN REFUSED FROM %.200s",
1237 get_canonical_hostname());
1239 /* The user has been authenticated and accepted. */
1240 packet_start(SSH_SMSG_SUCCESS);
1242 packet_write_wait();
1244 /* Perform session preparation. */
1245 do_authenticated(pw);
1248 #define AUTH_FAIL_MAX 6
1249 #define AUTH_FAIL_LOG (AUTH_FAIL_MAX/2)
1250 #define AUTH_FAIL_MSG "Too many authentication failures for %.100s"
1253 * read packets and try to authenticate local user *pw.
1254 * return if authentication is successfull
1257 do_authloop(struct passwd * pw)
1261 BIGNUM *client_host_key_e, *client_host_key_n;
1263 char *client_user = NULL, *password = NULL;
1265 int plen, dlen, nlen, ulen, elen;
1267 void (*authlog) (const char *fmt,...) = verbose;
1269 /* Indicate that authentication is needed. */
1270 packet_start(SSH_SMSG_FAILURE);
1272 packet_write_wait();
1274 for (attempt = 1;; attempt++) {
1275 int authenticated = 0;
1276 strlcpy(user, "", sizeof user);
1278 /* Get a packet from the client. */
1279 type = packet_read(&plen);
1281 /* Process the packet. */
1284 case SSH_CMSG_HAVE_KERBEROS_TGT:
1285 if (!options.kerberos_tgt_passing) {
1286 /* packet_get_all(); */
1287 verbose("Kerberos tgt passing disabled.");
1290 /* Accept Kerberos tgt. */
1291 char *tgt = packet_get_string(&dlen);
1292 packet_integrity_check(plen, 4 + dlen, type);
1293 if (!auth_kerberos_tgt(pw, tgt))
1294 verbose("Kerberos tgt REFUSED for %s", pw->pw_name);
1299 case SSH_CMSG_HAVE_AFS_TOKEN:
1300 if (!options.afs_token_passing || !k_hasafs()) {
1301 /* packet_get_all(); */
1302 verbose("AFS token passing disabled.");
1305 /* Accept AFS token. */
1306 char *token_string = packet_get_string(&dlen);
1307 packet_integrity_check(plen, 4 + dlen, type);
1308 if (!auth_afs_token(pw, token_string))
1309 verbose("AFS token REFUSED for %s", pw->pw_name);
1310 xfree(token_string);
1315 case SSH_CMSG_AUTH_KERBEROS:
1316 if (!options.kerberos_authentication) {
1317 /* packet_get_all(); */
1318 verbose("Kerberos authentication disabled.");
1321 /* Try Kerberos v4 authentication. */
1323 char *tkt_user = NULL;
1324 char *kdata = packet_get_string((unsigned int *) &auth.length);
1325 packet_integrity_check(plen, 4 + auth.length, type);
1327 if (auth.length < MAX_KTXT_LEN)
1328 memcpy(auth.dat, kdata, auth.length);
1331 authenticated = auth_krb4(pw->pw_name, &auth, &tkt_user);
1333 if (authenticated) {
1334 snprintf(user, sizeof user, " tktuser %s", tkt_user);
1341 case SSH_CMSG_AUTH_RHOSTS:
1342 if (!options.rhosts_authentication) {
1343 verbose("Rhosts authentication disabled.");
1347 * Get client user name. Note that we just have to
1348 * trust the client; this is one reason why rhosts
1349 * authentication is insecure. (Another is
1350 * IP-spoofing on a local network.)
1352 client_user = packet_get_string(&ulen);
1353 packet_integrity_check(plen, 4 + ulen, type);
1355 /* Try to authenticate using /etc/hosts.equiv and
1357 authenticated = auth_rhosts(pw, client_user);
1359 snprintf(user, sizeof user, " ruser %s", client_user);
1362 case SSH_CMSG_AUTH_RHOSTS_RSA:
1363 if (!options.rhosts_rsa_authentication) {
1364 verbose("Rhosts with RSA authentication disabled.");
1368 * Get client user name. Note that we just have to
1369 * trust the client; root on the client machine can
1370 * claim to be any user.
1372 client_user = packet_get_string(&ulen);
1374 /* Get the client host key. */
1375 client_host_key_e = BN_new();
1376 client_host_key_n = BN_new();
1377 bits = packet_get_int();
1378 packet_get_bignum(client_host_key_e, &elen);
1379 packet_get_bignum(client_host_key_n, &nlen);
1381 if (bits != BN_num_bits(client_host_key_n))
1382 error("Warning: keysize mismatch for client_host_key: "
1383 "actual %d, announced %d", BN_num_bits(client_host_key_n), bits);
1384 packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type);
1386 authenticated = auth_rhosts_rsa(pw, client_user,
1387 client_host_key_e, client_host_key_n);
1388 BN_clear_free(client_host_key_e);
1389 BN_clear_free(client_host_key_n);
1391 snprintf(user, sizeof user, " ruser %s", client_user);
1394 case SSH_CMSG_AUTH_RSA:
1395 if (!options.rsa_authentication) {
1396 verbose("RSA authentication disabled.");
1399 /* RSA authentication requested. */
1401 packet_get_bignum(n, &nlen);
1402 packet_integrity_check(plen, nlen, type);
1403 authenticated = auth_rsa(pw, n);
1407 case SSH_CMSG_AUTH_PASSWORD:
1408 if (!options.password_authentication) {
1409 verbose("Password authentication disabled.");
1413 * Read user password. It is in plain text, but was
1414 * transmitted over the encrypted channel so it is
1415 * not visible to an outside observer.
1417 password = packet_get_string(&dlen);
1418 packet_integrity_check(plen, 4 + dlen, type);
1421 /* Do PAM auth with password */
1422 authenticated = auth_pam_password(pw, password);
1424 /* Try authentication with the password. */
1425 authenticated = auth_password(pw, password);
1426 #endif /* USE_PAM */
1427 memset(password, 0, strlen(password));
1432 case SSH_CMSG_AUTH_TIS:
1433 debug("rcvd SSH_CMSG_AUTH_TIS");
1434 if (options.skey_authentication == 1) {
1435 char *skeyinfo = skey_keyinfo(pw->pw_name);
1436 if (skeyinfo == NULL) {
1437 debug("generating fake skeyinfo for %.100s.", pw->pw_name);
1438 skeyinfo = skey_fake_keyinfo(pw->pw_name);
1440 if (skeyinfo != NULL) {
1441 /* we send our s/key- in tis-challenge messages */
1442 debug("sending challenge '%s'", skeyinfo);
1443 packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE);
1444 packet_put_string(skeyinfo, strlen(skeyinfo));
1446 packet_write_wait();
1451 case SSH_CMSG_AUTH_TIS_RESPONSE:
1452 debug("rcvd SSH_CMSG_AUTH_TIS_RESPONSE");
1453 if (options.skey_authentication == 1) {
1454 char *response = packet_get_string(&dlen);
1455 debug("skey response == '%s'", response);
1456 packet_integrity_check(plen, 4 + dlen, type);
1457 authenticated = (skey_haskey(pw->pw_name) == 0 &&
1458 skey_passcheck(pw->pw_name, response) != -1);
1463 case SSH_CMSG_AUTH_TIS:
1464 /* TIS Authentication is unsupported */
1465 log("TIS authentication unsupported.");
1471 * Any unknown messages will be ignored (and failure
1472 * returned) during authentication.
1474 log("Unknown message during authentication: type %d", type);
1478 /* Raise logging level */
1479 if (authenticated ||
1480 attempt == AUTH_FAIL_LOG ||
1481 type == SSH_CMSG_AUTH_PASSWORD)
1484 authlog("%s %s for %.200s from %.200s port %d%s",
1485 authenticated ? "Accepted" : "Failed",
1487 pw->pw_uid == 0 ? "ROOT" : pw->pw_name,
1488 get_remote_ipaddr(),
1492 if (authenticated) {
1494 if (!do_pam_account(pw->pw_name, client_user))
1496 if (client_user != NULL)
1499 do_fake_authloop(pw->pw_name);
1501 #endif /* USE_PAM */
1505 if (client_user != NULL)
1508 if (attempt > AUTH_FAIL_MAX)
1509 packet_disconnect(AUTH_FAIL_MSG, pw->pw_name);
1511 /* Send a message indicating that the authentication attempt failed. */
1512 packet_start(SSH_SMSG_FAILURE);
1514 packet_write_wait();
1519 * The user does not exist or access is denied,
1520 * but fake indication that authentication is needed.
1523 do_fake_authloop(char *user)
1527 log("Faking authloop for illegal user %.200s from %.200s port %d",
1529 get_remote_ipaddr(),
1532 /* Indicate that authentication is needed. */
1533 packet_start(SSH_SMSG_FAILURE);
1535 packet_write_wait();
1538 * Keep reading packets, and always respond with a failure. This is
1539 * to avoid disclosing whether such a user really exists.
1541 for (attempt = 1;; attempt++) {
1542 /* Read a packet. This will not return if the client disconnects. */
1545 (void)packet_read(&plen);
1547 int type = packet_read(&plen);
1549 char *password, *skeyinfo;
1550 /* Try to send a fake s/key challenge. */
1551 if (options.skey_authentication == 1 &&
1552 (skeyinfo = skey_fake_keyinfo(user)) != NULL) {
1553 if (type == SSH_CMSG_AUTH_TIS) {
1554 packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE);
1555 packet_put_string(skeyinfo, strlen(skeyinfo));
1557 packet_write_wait();
1559 } else if (type == SSH_CMSG_AUTH_PASSWORD &&
1560 options.password_authentication &&
1561 (password = packet_get_string(&dlen)) != NULL &&
1563 strncasecmp(password, "s/key", 5) == 0 ) {
1564 packet_send_debug(skeyinfo);
1568 if (attempt > AUTH_FAIL_MAX)
1569 packet_disconnect(AUTH_FAIL_MSG, user);
1572 * Send failure. This should be indistinguishable from a
1573 * failed authentication.
1575 packet_start(SSH_SMSG_FAILURE);
1577 packet_write_wait();
1585 * Remove local Xauthority file.
1588 xauthfile_cleanup_proc(void *ignore)
1590 debug("xauthfile_cleanup_proc called");
1592 if (xauthfile != NULL) {
1600 * Prepares for an interactive session. This is called after the user has
1601 * been successfully authenticated. During this message exchange, pseudo
1602 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
1603 * are requested, etc.
1606 do_authenticated(struct passwd * pw)
1609 int compression_level = 0, enable_compression_after_reply = 0;
1610 int have_pty = 0, ptyfd = -1, ttyfd = -1, xauthfd = -1;
1611 int row, col, xpixel, ypixel, screen;
1613 char *command, *term = NULL, *display = NULL, *proto = NULL,
1621 * Cancel the alarm we set to limit the time taken for
1627 * Inform the channel mechanism that we are the server side and that
1628 * the client may request to connect to any port at all. (The user
1629 * could do it anyway, and we wouldn\'t know what is permitted except
1630 * by the client telling us, so we can equally well trust the client
1631 * not to request anything bogus.)
1633 channel_permit_all_opens();
1636 * We stay in this loop until the client requests to execute a shell
1642 /* Get a packet from the client. */
1643 type = packet_read(&plen);
1645 /* Process the packet. */
1647 case SSH_CMSG_REQUEST_COMPRESSION:
1648 packet_integrity_check(plen, 4, type);
1649 compression_level = packet_get_int();
1650 if (compression_level < 1 || compression_level > 9) {
1651 packet_send_debug("Received illegal compression level %d.",
1655 /* Enable compression after we have responded with SUCCESS. */
1656 enable_compression_after_reply = 1;
1659 case SSH_CMSG_REQUEST_PTY:
1661 debug("Allocating a pty not permitted for this authentication.");
1665 packet_disconnect("Protocol error: you already have a pty.");
1667 debug("Allocating pty.");
1669 /* Allocate a pty and open it. */
1670 if (!pty_allocate(&ptyfd, &ttyfd, ttyname,
1672 error("Failed to allocate pty.");
1675 /* Determine the group to make the owner of the tty. */
1676 grp = getgrnam("tty");
1678 tty_gid = grp->gr_gid;
1679 tty_mode = S_IRUSR | S_IWUSR | S_IWGRP;
1681 tty_gid = pw->pw_gid;
1682 tty_mode = S_IRUSR | S_IWUSR | S_IWGRP | S_IWOTH;
1685 /* Change ownership of the tty. */
1686 if (chown(ttyname, pw->pw_uid, tty_gid) < 0)
1687 fatal("chown(%.100s, %d, %d) failed: %.100s",
1688 ttyname, pw->pw_uid, tty_gid, strerror(errno));
1689 if (chmod(ttyname, tty_mode) < 0)
1690 fatal("chmod(%.100s, 0%o) failed: %.100s",
1691 ttyname, tty_mode, strerror(errno));
1693 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
1694 term = packet_get_string(&dlen);
1695 packet_integrity_check(dlen, strlen(term), type);
1696 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
1697 /* Remaining bytes */
1698 n_bytes = plen - (4 + dlen + 4 * 4);
1700 if (strcmp(term, "") == 0)
1703 /* Get window size from the packet. */
1704 row = packet_get_int();
1705 col = packet_get_int();
1706 xpixel = packet_get_int();
1707 ypixel = packet_get_int();
1708 pty_change_window_size(ptyfd, row, col, xpixel, ypixel);
1710 /* Get tty modes from the packet. */
1711 tty_parse_modes(ttyfd, &n_bytes);
1712 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
1714 /* Indicate that we now have a pty. */
1718 /* do the pam_open_session since we have the pty */
1719 do_pam_session(pw->pw_name, ttyname);
1720 #endif /* USE_PAM */
1724 case SSH_CMSG_X11_REQUEST_FORWARDING:
1725 if (!options.x11_forwarding) {
1726 packet_send_debug("X11 forwarding disabled in server configuration file.");
1730 if (no_x11_forwarding_flag) {
1731 packet_send_debug("X11 forwarding not permitted for this authentication.");
1734 debug("Received request for X11 forwarding with auth spoofing.");
1736 packet_disconnect("Protocol error: X11 display already set.");
1738 int proto_len, data_len;
1739 proto = packet_get_string(&proto_len);
1740 data = packet_get_string(&data_len);
1741 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
1743 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
1744 screen = packet_get_int();
1747 display = x11_create_display_inet(screen, options.x11_display_offset);
1751 /* Setup to always have a local .Xauthority. */
1752 xauthfile = xmalloc(MAXPATHLEN);
1753 snprintf(xauthfile, MAXPATHLEN, "/tmp/XauthXXXXXX");
1755 if ((xauthfd = mkstemp(xauthfile)) != -1) {
1756 fchown(xauthfd, pw->pw_uid, pw->pw_gid);
1758 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
1764 #else /* XAUTH_PATH */
1765 packet_send_debug("No xauth program; cannot forward with spoofing.");
1767 #endif /* XAUTH_PATH */
1769 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
1770 if (no_agent_forwarding_flag) {
1771 debug("Authentication agent forwarding not permitted for this authentication.");
1774 debug("Received authentication agent forwarding request.");
1775 auth_input_request_forwarding(pw);
1778 case SSH_CMSG_PORT_FORWARD_REQUEST:
1779 if (no_port_forwarding_flag) {
1780 debug("Port forwarding not permitted for this authentication.");
1783 debug("Received TCP/IP port forwarding request.");
1784 channel_input_port_forward_request(pw->pw_uid == 0);
1787 case SSH_CMSG_MAX_PACKET_SIZE:
1788 if (packet_set_maxsize(packet_get_int()) < 0)
1792 case SSH_CMSG_EXEC_SHELL:
1793 /* Set interactive/non-interactive mode. */
1794 packet_set_interactive(have_pty || display != NULL,
1795 options.keepalives);
1799 #endif /* USE_PAM */
1800 if (forced_command != NULL)
1801 goto do_forced_command;
1802 debug("Forking shell.");
1803 packet_integrity_check(plen, 0, type);
1805 do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1807 do_exec_no_pty(NULL, pw, display, proto, data);
1810 case SSH_CMSG_EXEC_CMD:
1811 /* Set interactive/non-interactive mode. */
1812 packet_set_interactive(have_pty || display != NULL,
1813 options.keepalives);
1817 #endif /* USE_PAM */
1818 if (forced_command != NULL)
1819 goto do_forced_command;
1820 /* Get command from the packet. */
1823 command = packet_get_string(&dlen);
1824 debug("Executing command '%.500s'", command);
1825 packet_integrity_check(plen, 4 + dlen, type);
1828 do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1830 do_exec_no_pty(command, pw, display, proto, data);
1836 * Any unknown messages in this phase are ignored,
1837 * and a failure message is returned.
1839 log("Unknown packet type received after authentication: %d", type);
1843 /* The request was successfully processed. */
1844 packet_start(SSH_SMSG_SUCCESS);
1846 packet_write_wait();
1848 /* Enable compression now that we have replied if appropriate. */
1849 if (enable_compression_after_reply) {
1850 enable_compression_after_reply = 0;
1851 packet_start_compression(compression_level);
1856 /* The request failed. */
1857 packet_start(SSH_SMSG_FAILURE);
1859 packet_write_wait();
1864 * There is a forced command specified for this login.
1867 debug("Executing forced command: %.900s", forced_command);
1869 do_exec_pty(forced_command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1871 do_exec_no_pty(forced_command, pw, display, proto, data);
1877 * This is called to fork and execute a command when we have no tty. This
1878 * will call do_child from the child, and server_loop from the parent after
1879 * setting up file descriptors and such.
1882 do_exec_no_pty(const char *command, struct passwd * pw,
1883 const char *display, const char *auth_proto,
1884 const char *auth_data)
1889 int pin[2], pout[2], perr[2];
1890 /* Allocate pipes for communicating with the program. */
1891 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
1892 packet_disconnect("Could not create pipes: %.100s",
1894 #else /* USE_PIPES */
1895 int inout[2], err[2];
1896 /* Uses socket pairs to communicate with the program. */
1897 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
1898 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
1899 packet_disconnect("Could not create socket pairs: %.100s",
1901 #endif /* USE_PIPES */
1903 setproctitle("%s@notty", pw->pw_name);
1905 /* Fork the child. */
1906 if ((pid = fork()) == 0) {
1907 /* Child. Reinitialize the log since the pid has changed. */
1908 log_init(av0, options.log_level, options.log_facility, log_stderr);
1911 * Create a new session and process group since the 4.4BSD
1912 * setlogin() affects the entire process group.
1915 error("setsid failed: %.100s", strerror(errno));
1919 * Redirect stdin. We close the parent side of the socket
1920 * pair, and make the child side the standard input.
1923 if (dup2(pin[0], 0) < 0)
1924 perror("dup2 stdin");
1927 /* Redirect stdout. */
1929 if (dup2(pout[1], 1) < 0)
1930 perror("dup2 stdout");
1933 /* Redirect stderr. */
1935 if (dup2(perr[1], 2) < 0)
1936 perror("dup2 stderr");
1938 #else /* USE_PIPES */
1940 * Redirect stdin, stdout, and stderr. Stdin and stdout will
1941 * use the same socket, as some programs (particularly rdist)
1942 * seem to depend on it.
1946 if (dup2(inout[0], 0) < 0) /* stdin */
1947 perror("dup2 stdin");
1948 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
1949 perror("dup2 stdout");
1950 if (dup2(err[0], 2) < 0) /* stderr */
1951 perror("dup2 stderr");
1952 #endif /* USE_PIPES */
1954 /* Do processing for the child (exec command etc). */
1955 do_child(command, pw, NULL, display, auth_proto, auth_data, NULL);
1959 packet_disconnect("fork failed: %.100s", strerror(errno));
1961 /* We are the parent. Close the child sides of the pipes. */
1966 /* Enter the interactive session. */
1967 server_loop(pid, pin[1], pout[0], perr[0]);
1968 /* server_loop has closed pin[1], pout[1], and perr[1]. */
1969 #else /* USE_PIPES */
1970 /* We are the parent. Close the child sides of the socket pairs. */
1975 * Enter the interactive session. Note: server_loop must be able to
1976 * handle the case that fdin and fdout are the same.
1978 server_loop(pid, inout[1], inout[1], err[1]);
1979 /* server_loop has closed inout[1] and err[1]. */
1980 #endif /* USE_PIPES */
1983 struct pty_cleanup_context {
1984 const char *ttyname;
1989 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
1990 * dropped connection).
1993 pty_cleanup_proc(void *context)
1995 struct pty_cleanup_context *cu = context;
1997 debug("pty_cleanup_proc called");
1999 /* Record that the user has logged out. */
2000 record_logout(cu->pid, cu->ttyname);
2002 /* Release the pseudo-tty. */
2003 pty_release(cu->ttyname);
2007 * This is called to fork and execute a command when we have a tty. This
2008 * will call do_child from the child, and server_loop from the parent after
2009 * setting up file descriptors, controlling tty, updating wtmp, utmp,
2010 * lastlog, and other such operations.
2013 do_exec_pty(const char *command, int ptyfd, int ttyfd,
2014 const char *ttyname, struct passwd * pw, const char *term,
2015 const char *display, const char *auth_proto,
2016 const char *auth_data)
2019 const char *hostname;
2020 time_t last_login_time;
2021 char buf[100], *time_string;
2026 struct sockaddr_storage from;
2028 struct pty_cleanup_context cleanup_context;
2030 /* Get remote host name. */
2031 hostname = get_canonical_hostname();
2034 * Get the time when the user last logged in. Buf will be set to
2035 * contain the hostname the last login was from.
2037 if (!options.use_login) {
2038 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
2041 setproctitle("%s@%s", pw->pw_name, strrchr(ttyname, '/') + 1);
2043 /* Fork the child. */
2044 if ((pid = fork()) == 0) {
2047 /* Child. Reinitialize the log because the pid has
2049 log_init(av0, options.log_level, options.log_facility, log_stderr);
2051 /* Close the master side of the pseudo tty. */
2054 /* Make the pseudo tty our controlling tty. */
2055 pty_make_controlling_tty(&ttyfd, ttyname);
2057 /* Redirect stdin from the pseudo tty. */
2058 if (dup2(ttyfd, fileno(stdin)) < 0)
2059 error("dup2 stdin failed: %.100s", strerror(errno));
2061 /* Redirect stdout to the pseudo tty. */
2062 if (dup2(ttyfd, fileno(stdout)) < 0)
2063 error("dup2 stdin failed: %.100s", strerror(errno));
2065 /* Redirect stderr to the pseudo tty. */
2066 if (dup2(ttyfd, fileno(stderr)) < 0)
2067 error("dup2 stdin failed: %.100s", strerror(errno));
2069 /* Close the extra descriptor for the pseudo tty. */
2073 * Get IP address of client. This is needed because we want
2074 * to record where the user logged in from. If the
2075 * connection is not a socket, let the ip address be 0.0.0.0.
2077 memset(&from, 0, sizeof(from));
2078 if (packet_get_connection_in() == packet_get_connection_out()) {
2079 fromlen = sizeof(from);
2080 if (getpeername(packet_get_connection_in(),
2081 (struct sockaddr *) & from, &fromlen) < 0) {
2082 debug("getpeername: %.100s", strerror(errno));
2086 /* Record that there was a login on that terminal. */
2087 record_login(pid, ttyname, pw->pw_name, pw->pw_uid, hostname,
2088 (struct sockaddr *)&from);
2090 /* Check if .hushlogin exists. */
2091 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
2092 quiet_login = stat(line, &st) >= 0;
2096 print_pam_messages();
2097 #endif /* USE_PAM */
2100 * If the user has logged in before, display the time of last
2101 * login. However, don't display anything extra if a command
2102 * has been specified (so that ssh can be used to execute
2103 * commands on a remote machine without users knowing they
2104 * are going to another machine). Login(1) will do this for
2105 * us as well, so check if login(1) is used
2107 if (command == NULL && last_login_time != 0 && !quiet_login &&
2108 !options.use_login) {
2109 /* Convert the date to a string. */
2110 time_string = ctime(&last_login_time);
2111 /* Remove the trailing newline. */
2112 if (strchr(time_string, '\n'))
2113 *strchr(time_string, '\n') = 0;
2114 /* Display the last login time. Host if displayed
2116 if (strcmp(buf, "") == 0)
2117 printf("Last login: %s\r\n", time_string);
2119 printf("Last login: %s from %s\r\n", time_string, buf);
2122 * Print /etc/motd unless a command was specified or printing
2123 * it was disabled in server options or login(1) will be
2124 * used. Note that some machines appear to print it in
2125 * /etc/profile or similar.
2127 if (command == NULL && options.print_motd && !quiet_login &&
2128 !options.use_login) {
2129 /* Print /etc/motd if it exists. */
2130 f = fopen("/etc/motd", "r");
2132 while (fgets(line, sizeof(line), f))
2133 fputs(line, stdout);
2137 /* Do common processing for the child, such as execing the command. */
2138 do_child(command, pw, term, display, auth_proto, auth_data, ttyname);
2142 packet_disconnect("fork failed: %.100s", strerror(errno));
2143 /* Parent. Close the slave side of the pseudo tty. */
2147 * Create another descriptor of the pty master side for use as the
2148 * standard input. We could use the original descriptor, but this
2149 * simplifies code in server_loop. The descriptor is bidirectional.
2153 packet_disconnect("dup failed: %.100s", strerror(errno));
2156 * Add a cleanup function to clear the utmp entry and record logout
2157 * time in case we call fatal() (e.g., the connection gets closed).
2159 cleanup_context.pid = pid;
2160 cleanup_context.ttyname = ttyname;
2161 fatal_add_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
2163 /* Enter interactive session. */
2164 server_loop(pid, ptyfd, fdout, -1);
2165 /* server_loop has not closed ptyfd and fdout. */
2167 /* Cancel the cleanup function. */
2168 fatal_remove_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
2170 /* Record that the user has logged out. */
2171 record_logout(pid, ttyname);
2173 /* Release the pseudo-tty. */
2174 pty_release(ttyname);
2177 * Close the server side of the socket pairs. We must do this after
2178 * the pty cleanup, so that another process doesn't get this pty
2179 * while we're still cleaning up.
2186 * Sets the value of the given variable in the environment. If the variable
2187 * already exists, its value is overriden.
2190 child_set_env(char ***envp, unsigned int *envsizep, const char *name,
2193 unsigned int i, namelen;
2197 * Find the slot where the value should be stored. If the variable
2198 * already exists, we reuse the slot; otherwise we append a new slot
2199 * at the end of the array, expanding if necessary.
2202 namelen = strlen(name);
2203 for (i = 0; env[i]; i++)
2204 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2207 /* Reuse the slot. */
2210 /* New variable. Expand if necessary. */
2211 if (i >= (*envsizep) - 1) {
2213 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
2215 /* Need to set the NULL pointer at end of array beyond the new slot. */
2219 /* Allocate space and format the variable in the appropriate slot. */
2220 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2221 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2225 * Reads environment variables from the given file and adds/overrides them
2226 * into the environment. If the file does not exist, this does nothing.
2227 * Otherwise, it must consist of empty lines, comments (line starts with '#')
2228 * and assignments of the form name=value. No other forms are allowed.
2231 read_environment_file(char ***env, unsigned int *envsize,
2232 const char *filename)
2238 f = fopen(filename, "r");
2242 while (fgets(buf, sizeof(buf), f)) {
2243 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
2245 if (!*cp || *cp == '#' || *cp == '\n')
2247 if (strchr(cp, '\n'))
2248 *strchr(cp, '\n') = '\0';
2249 value = strchr(cp, '=');
2250 if (value == NULL) {
2251 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
2254 /* Replace the equals sign by nul, and advance value to the value string. */
2257 child_set_env(env, envsize, cp, value);
2264 * Sets any environment variables which have been specified by PAM
2266 void do_pam_environment(char ***env, int *envsize)
2268 char *equals, var_name[512], var_val[512];
2272 if ((pam_env = fetch_pam_environment()) == NULL)
2275 for(i = 0; pam_env[i] != NULL; i++) {
2276 if ((equals = strstr(pam_env[i], "=")) == NULL)
2279 if (strlen(pam_env[i]) < (sizeof(var_name) - 1))
2281 memset(var_name, '\0', sizeof(var_name));
2282 memset(var_val, '\0', sizeof(var_val));
2284 strncpy(var_name, pam_env[i], equals - pam_env[i]);
2285 strcpy(var_val, equals + 1);
2287 debug("PAM environment: %s=%s", var_name, var_val);
2289 child_set_env(env, envsize, var_name, var_val);
2293 #endif /* USE_PAM */
2296 * Performs common processing for the child, such as setting up the
2297 * environment, closing extra file descriptors, setting the user and group
2298 * ids, and executing the command or shell.
2301 do_child(const char *command, struct passwd * pw, const char *term,
2302 const char *display, const char *auth_proto,
2303 const char *auth_data, const char *ttyname)
2305 const char *shell, *cp = NULL;
2308 unsigned int envsize, i;
2310 extern char **environ;
2314 #ifndef USE_PAM /* pam_nologin handles this */
2315 /* Check /etc/nologin. */
2316 f = fopen("/etc/nologin", "r");
2318 /* /etc/nologin exists. Print its contents and exit. */
2319 while (fgets(buf, sizeof(buf), f))
2322 if (pw->pw_uid != 0)
2325 #endif /* USE_PAM */
2327 /* Set login name in the kernel. */
2328 if (setlogin(pw->pw_name) < 0)
2329 error("setlogin failed: %s", strerror(errno));
2331 /* Set uid, gid, and groups. */
2332 /* Login(1) does this as well, and it needs uid 0 for the "-h"
2333 switch, so we let login(1) to this for us. */
2334 if (!options.use_login) {
2335 if (getuid() == 0 || geteuid() == 0) {
2336 if (setgid(pw->pw_gid) < 0) {
2340 /* Initialize the group list. */
2341 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
2342 perror("initgroups");
2347 /* Permanently switch to the desired uid. */
2348 permanently_set_uid(pw->pw_uid);
2350 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
2351 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
2354 * Get the shell from the password data. An empty shell field is
2355 * legal, and means /bin/sh.
2357 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
2360 /* Try to get AFS tokens for the local cell. */
2364 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
2365 krb_afslog(cell, 0);
2371 /* Initialize the environment. */
2373 env = xmalloc(envsize * sizeof(char *));
2376 if (!options.use_login) {
2377 /* Set basic environment. */
2378 child_set_env(&env, &envsize, "USER", pw->pw_name);
2379 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
2380 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
2381 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
2383 snprintf(buf, sizeof buf, "%.200s/%.50s",
2384 _PATH_MAILDIR, pw->pw_name);
2385 child_set_env(&env, &envsize, "MAIL", buf);
2387 /* Normal systems set SHELL by default. */
2388 child_set_env(&env, &envsize, "SHELL", shell);
2391 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
2393 /* Set custom environment options from RSA authentication. */
2394 while (custom_environment) {
2395 struct envstring *ce = custom_environment;
2398 for (i = 0; s[i] != '=' && s[i]; i++);
2401 child_set_env(&env, &envsize, s, s + i + 1);
2403 custom_environment = ce->next;
2408 snprintf(buf, sizeof buf, "%.50s %d %d",
2409 get_remote_ipaddr(), get_remote_port(), get_local_port());
2410 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
2413 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
2415 child_set_env(&env, &envsize, "TERM", term);
2417 child_set_env(&env, &envsize, "DISPLAY", display);
2421 extern char *ticket;
2424 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
2429 /* Pull in any environment variables that may have been set by PAM. */
2430 do_pam_environment(&env, &envsize);
2431 #endif /* USE_PAM */
2434 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
2436 if (auth_get_socket_name() != NULL)
2437 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
2438 auth_get_socket_name());
2440 /* read $HOME/.ssh/environment. */
2441 if (!options.use_login) {
2442 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
2443 read_environment_file(&env, &envsize, buf);
2446 /* dump the environment */
2447 fprintf(stderr, "Environment:\n");
2448 for (i = 0; env[i]; i++)
2449 fprintf(stderr, " %.200s\n", env[i]);
2452 * Close the connection descriptors; note that this is the child, and
2453 * the server will still have the socket open, and it is important
2454 * that we do not shutdown it. Note that the descriptors cannot be
2455 * closed before building the environment, as we call
2456 * get_remote_ipaddr there.
2458 if (packet_get_connection_in() == packet_get_connection_out())
2459 close(packet_get_connection_in());
2461 close(packet_get_connection_in());
2462 close(packet_get_connection_out());
2465 * Close all descriptors related to channels. They will still remain
2466 * open in the parent.
2468 /* XXX better use close-on-exec? -markus */
2469 channel_close_all();
2472 * Close any extra file descriptors. Note that there may still be
2473 * descriptors left by system functions. They will be closed later.
2478 * Close any extra open file descriptors so that we don\'t have them
2479 * hanging around in clients. Note that we want to do this after
2480 * initgroups, because at least on Solaris 2.3 it leaves file
2483 for (i = 3; i < 64; i++)
2486 /* Change current directory to the user\'s home directory. */
2487 if (chdir(pw->pw_dir) < 0)
2488 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
2489 pw->pw_dir, strerror(errno));
2492 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
2493 * xauth are run in the proper environment.
2498 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
2501 if (!options.use_login) {
2502 if (stat(SSH_USER_RC, &st) >= 0) {
2504 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
2506 f = popen("/bin/sh " SSH_USER_RC, "w");
2508 if (auth_proto != NULL && auth_data != NULL)
2509 fprintf(f, "%s %s\n", auth_proto, auth_data);
2512 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
2513 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
2515 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
2517 f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
2519 if (auth_proto != NULL && auth_data != NULL)
2520 fprintf(f, "%s %s\n", auth_proto, auth_data);
2523 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
2527 /* Add authority data to .Xauthority if appropriate. */
2528 if (auth_proto != NULL && auth_data != NULL) {
2530 fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
2531 XAUTH_PATH, display, auth_proto, auth_data);
2533 f = popen(XAUTH_PATH " -q -", "w");
2535 fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
2538 fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
2541 #endif /* XAUTH_PATH */
2543 /* Get the last component of the shell name. */
2544 cp = strrchr(shell, '/');
2551 * If we have no command, execute the shell. In this case, the shell
2552 * name to be passed in argv[0] is preceded by '-' to indicate that
2553 * this is a login shell.
2556 if (!options.use_login) {
2560 * Check for mail if we have a tty and it was enabled
2561 * in server options.
2563 if (ttyname && options.check_mail) {
2565 struct stat mailstat;
2566 mailbox = getenv("MAIL");
2567 if (mailbox != NULL) {
2568 if (stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0)
2569 printf("No mail.\n");
2570 else if (mailstat.st_mtime < mailstat.st_atime)
2571 printf("You have mail.\n");
2573 printf("You have new mail.\n");
2576 /* Start the shell. Set initial character to '-'. */
2578 strncpy(buf + 1, cp, sizeof(buf) - 1);
2579 buf[sizeof(buf) - 1] = 0;
2581 /* Execute the shell. */
2584 execve(shell, argv, env);
2586 /* Executing the shell failed. */
2591 /* Launch login(1). */
2593 execl(LOGIN_PROGRAM, "login", "-h", get_remote_ipaddr(),
2594 "-p", "-f", "--", pw->pw_name, NULL);
2596 /* Login couldn't be executed, die. */
2603 * Execute the command using the user's shell. This uses the -c
2604 * option to execute the command.
2606 argv[0] = (char *) cp;
2608 argv[2] = (char *) command;
2610 execve(shell, argv, env);