2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * Created: Sat Mar 18 16:36:11 1995 ylo
6 * Ssh client program. This program can be used to log into a remote machine.
7 * The software supports strong authentication, encryption, and forwarding
8 * of X11, TCP/IP, and authentication connections.
10 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu> in Canada.
24 #ifdef HAVE___PROGNAME
25 extern char *__progname;
26 #else /* HAVE___PROGNAME */
27 const char *__progname = "ssh";
28 #endif /* HAVE___PROGNAME */
30 /* Flag indicating whether IPv4 or IPv6. This can be set on the command line.
31 Default value is AF_UNSPEC means both IPv4 and IPv6. */
33 int IPv4or6 = AF_INET;
35 int IPv4or6 = AF_UNSPEC;
38 /* Flag indicating whether debug mode is on. This can be set on the command line. */
44 * Flag indicating that nothing should be read from stdin. This can be set
45 * on the command line.
47 int stdin_null_flag = 0;
50 * Flag indicating that ssh should fork after authentication. This is useful
51 * so that the pasphrase can be entered manually, and then ssh goes to the
54 int fork_after_authentication_flag = 0;
57 * General data structure for command line options and options configurable
58 * in configuration files. See readconf.h.
63 * Name of the host we are connecting to. This is the name given on the
64 * command line, or the HostName specified for the user-supplied name in a
69 /* socket address the host resolves to */
70 struct sockaddr_storage hostaddr;
73 * Flag to indicate that we have received a window change signal which has
74 * not yet been processed. This will cause a message indicating the new
75 * window size to be sent to the server a little later. This is volatile
76 * because this is updated in a signal handler.
78 volatile int received_window_change_signal = 0;
80 /* Value of argv[0] (set in the main program). */
83 /* Flag indicating whether we have a valid host private key loaded. */
84 int host_private_key_loaded = 0;
86 /* Host private key. */
87 RSA *host_private_key = NULL;
89 /* Original real UID. */
90 uid_t original_real_uid;
92 /* Prints a help message to the user. This function never returns. */
97 fprintf(stderr, "Usage: %s [options] host [command]\n", av0);
98 fprintf(stderr, "Options:\n");
99 fprintf(stderr, " -l user Log in using this user name.\n");
100 fprintf(stderr, " -n Redirect input from /dev/null.\n");
101 fprintf(stderr, " -a Disable authentication agent forwarding.\n");
103 fprintf(stderr, " -k Disable Kerberos ticket and AFS token forwarding.\n");
105 fprintf(stderr, " -x Disable X11 connection forwarding.\n");
106 fprintf(stderr, " -X Enable X11 connection forwarding.\n");
107 fprintf(stderr, " -i file Identity for RSA authentication (default: ~/.ssh/identity).\n");
108 fprintf(stderr, " -t Tty; allocate a tty even if command is given.\n");
109 fprintf(stderr, " -v Verbose; display verbose debugging messages.\n");
110 fprintf(stderr, " -V Display version number only.\n");
111 fprintf(stderr, " -P Don't allocate a privileged port.\n");
112 fprintf(stderr, " -q Quiet; don't display any warning messages.\n");
113 fprintf(stderr, " -f Fork into background after authentication.\n");
114 fprintf(stderr, " -e char Set escape character; ``none'' = disable (default: ~).\n");
116 fprintf(stderr, " -c cipher Select encryption algorithm: "
119 fprintf(stderr, " -p port Connect to this port. Server must be on the same port.\n");
120 fprintf(stderr, " -L listen-port:host:port Forward local port to remote address\n");
121 fprintf(stderr, " -R listen-port:host:port Forward remote port to local address\n");
122 fprintf(stderr, " These cause %s to listen for connections on a port, and\n", av0);
123 fprintf(stderr, " forward them to the other side by connecting to host:port.\n");
124 fprintf(stderr, " -C Enable compression.\n");
125 fprintf(stderr, " -g Allow remote hosts to connect to forwarded ports.\n");
126 fprintf(stderr, " -4 Use IPv4 only.\n");
127 fprintf(stderr, " -6 Use IPv6 only.\n");
128 fprintf(stderr, " -o 'option' Process the option as if it was read from a configuration file.\n");
133 * Connects to the given host using rsh (or prints an error message and exits
134 * if rsh is not available). This function never returns.
137 rsh_connect(char *host, char *user, Buffer * command)
142 log("Using rsh. WARNING: Connection will not be encrypted.");
143 /* Build argument list for rsh. */
145 args[i++] = _PATH_RSH;
146 /* host may have to come after user on some systems */
152 if (buffer_len(command) > 0) {
153 buffer_append(command, "\0", 1);
154 args[i++] = buffer_ptr(command);
158 for (i = 0; args[i]; i++) {
160 fprintf(stderr, " ");
161 fprintf(stderr, "%s", args[i]);
163 fprintf(stderr, "\n");
165 execv(_PATH_RSH, args);
171 * Main program for the ssh client.
174 main(int ac, char **av)
176 int i, opt, optind, type, exit_status, ok, authfd;
177 u_short fwd_port, fwd_host_port;
178 char *optarg, *cp, buf[256];
182 struct passwd *pw, pwcopy;
183 int interactive = 0, dummy;
184 uid_t original_effective_uid;
188 * Save the original real uid. It will be needed later (uid-swapping
189 * may clobber the real uid).
191 original_real_uid = getuid();
192 original_effective_uid = geteuid();
194 /* If we are installed setuid root be careful to not drop core. */
195 if (original_real_uid != original_effective_uid) {
197 rlim.rlim_cur = rlim.rlim_max = 0;
198 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
199 fatal("setrlimit failed: %.100s", strerror(errno));
202 * Use uid-swapping to give up root privileges for the duration of
203 * option processing. We will re-instantiate the rights when we are
204 * ready to create the privileged port, and will permanently drop
205 * them when the port has been created (actually, when the connection
206 * has been made, as we may need to create the port several times).
208 temporarily_use_uid(original_real_uid);
211 * Set our umask to something reasonable, as some files are created
212 * with the default umask. This will make them world-readable but
213 * writable only by the owner, which is ok for all files for which we
214 * don't set the modes explicitly.
218 /* Save our own name. */
221 /* Initialize option structure to indicate that no values have been set. */
222 initialize_options(&options);
224 /* Parse command-line arguments. */
227 /* If program name is not one of the standard names, use it as host name. */
228 if (strchr(av0, '/'))
229 cp = strrchr(av0, '/') + 1;
232 if (strcmp(cp, "rsh") != 0 && strcmp(cp, "ssh") != 0 &&
233 strcmp(cp, "rlogin") != 0 && strcmp(cp, "slogin") != 0)
236 for (optind = 1; optind < ac; optind++) {
237 if (av[optind][0] != '-') {
240 if ((cp = strchr(av[optind], '@'))) {
243 options.user = av[optind];
253 if (strchr("eilcpLRo", opt)) { /* options with arguments */
254 optarg = av[optind] + 2;
255 if (strcmp(optarg, "") == 0) {
256 if (optind >= ac - 1)
258 optarg = av[++optind];
279 fork_after_authentication_flag = 1;
284 options.forward_x11 = 0;
288 options.forward_x11 = 1;
292 options.gateway_ports = 1;
296 options.use_privileged_port = 0;
300 options.forward_agent = 0;
304 options.kerberos_tgt_passing = 0;
305 options.afs_token_passing = 0;
309 if (stat(optarg, &st) < 0) {
310 fprintf(stderr, "Warning: Identity file %s does not exist.\n",
314 if (options.num_identity_files >= SSH_MAX_IDENTITY_FILES)
315 fatal("Too many identity files specified (max %d)",
316 SSH_MAX_IDENTITY_FILES);
317 options.identity_files[options.num_identity_files++] =
327 fprintf(stderr, "SSH Version %s, protocol version %d.%d.\n",
328 SSH_VERSION, PROTOCOL_MAJOR, PROTOCOL_MINOR);
329 fprintf(stderr, "Compiled with SSL.\n");
333 options.log_level = SYSLOG_LEVEL_DEBUG;
337 options.log_level = SYSLOG_LEVEL_QUIET;
341 if (optarg[0] == '^' && optarg[2] == 0 &&
342 (unsigned char) optarg[1] >= 64 && (unsigned char) optarg[1] < 128)
343 options.escape_char = (unsigned char) optarg[1] & 31;
344 else if (strlen(optarg) == 1)
345 options.escape_char = (unsigned char) optarg[0];
346 else if (strcmp(optarg, "none") == 0)
347 options.escape_char = -2;
349 fprintf(stderr, "Bad escape character '%s'.\n", optarg);
355 options.cipher = cipher_number(optarg);
356 if (options.cipher == -1) {
357 fprintf(stderr, "Unknown cipher type '%s'\n", optarg);
363 options.port = atoi(optarg);
367 options.user = optarg;
371 if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf,
372 &fwd_host_port) != 3 &&
373 sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
374 &fwd_host_port) != 3) {
375 fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
379 add_remote_forward(&options, fwd_port, buf, fwd_host_port);
383 if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf,
384 &fwd_host_port) != 3 &&
385 sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
386 &fwd_host_port) != 3) {
387 fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
391 add_local_forward(&options, fwd_port, buf, fwd_host_port);
395 options.compression = 1;
400 if (process_config_line(&options, host ? host : "", optarg,
401 "command-line", 0, &dummy) != 0)
410 /* Check that we got a host name. */
414 /* check if RSA support exists */
415 if (rsa_alive() == 0) {
417 "%s: no RSA support in libssl and libcrypto. See ssl(8).\n",
421 /* Initialize the command to execute on remote host. */
422 buffer_init(&command);
425 * Save the command to execute on the remote host in a buffer. There
426 * is no limit on the length of the command, except by the maximum
427 * packet size. Also sets the tty flag if there is no command.
430 /* No command specified - execute shell on a tty. */
433 /* A command has been specified. Store it into the
435 for (i = optind; i < ac; i++) {
437 buffer_append(&command, " ", 1);
438 buffer_append(&command, av[i], strlen(av[i]));
442 /* Cannot fork to background if no command. */
443 if (fork_after_authentication_flag && buffer_len(&command) == 0)
444 fatal("Cannot fork into background without a command to execute.");
446 /* Allocate a tty by default if no command specified. */
447 if (buffer_len(&command) == 0)
450 /* Do not allocate a tty if stdin is not a tty. */
451 if (!isatty(fileno(stdin))) {
453 fprintf(stderr, "Pseudo-terminal will not be allocated because stdin is not a terminal.\n");
457 pw = getpwuid(original_real_uid);
459 fprintf(stderr, "You don't exist, go away!\n");
462 /* Take a copy of the returned structure. */
463 memset(&pwcopy, 0, sizeof(pwcopy));
464 pwcopy.pw_name = xstrdup(pw->pw_name);
465 pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
466 pwcopy.pw_uid = pw->pw_uid;
467 pwcopy.pw_gid = pw->pw_gid;
468 pwcopy.pw_dir = xstrdup(pw->pw_dir);
469 pwcopy.pw_shell = xstrdup(pw->pw_shell);
472 /* Initialize "log" output. Since we are the client all output
473 actually goes to the terminal. */
474 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0);
476 /* Read per-user configuration file. */
477 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_CONFFILE);
478 read_config_file(buf, host, &options);
480 /* Read systemwide configuration file. */
481 read_config_file(HOST_CONFIG_FILE, host, &options);
483 /* Fill configuration defaults. */
484 fill_default_options(&options);
487 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0);
489 if (options.user == NULL)
490 options.user = xstrdup(pw->pw_name);
492 if (options.hostname != NULL)
493 host = options.hostname;
495 /* Find canonic host name. */
496 if (strchr(host, '.') == 0) {
497 struct addrinfo hints;
498 struct addrinfo *ai = NULL;
500 memset(&hints, 0, sizeof(hints));
501 hints.ai_family = IPv4or6;
502 hints.ai_flags = AI_CANONNAME;
503 hints.ai_socktype = SOCK_STREAM;
504 errgai = getaddrinfo(host, NULL, &hints, &ai);
506 if (ai->ai_canonname != NULL)
507 host = xstrdup(ai->ai_canonname);
511 /* Disable rhosts authentication if not running as root. */
512 if (original_effective_uid != 0 || !options.use_privileged_port) {
513 options.rhosts_authentication = 0;
514 options.rhosts_rsa_authentication = 0;
517 * If using rsh has been selected, exec it now (without trying
518 * anything else). Note that we must release privileges first.
520 if (options.use_rsh) {
522 * Restore our superuser privileges. This must be done
523 * before permanently setting the uid.
527 /* Switch to the original uid permanently. */
528 permanently_set_uid(original_real_uid);
531 rsh_connect(host, options.user, &command);
532 fatal("rsh_connect returned");
534 /* Restore our superuser privileges. */
538 * Open a connection to the remote host. This needs root privileges
539 * if rhosts_{rsa_}authentication is enabled.
542 ok = ssh_connect(host, &hostaddr, options.port,
543 options.connection_attempts,
544 !options.rhosts_authentication &&
545 !options.rhosts_rsa_authentication,
547 options.proxy_command);
550 * If we successfully made the connection, load the host private key
551 * in case we will need it later for combined rsa-rhosts
552 * authentication. This must be done before releasing extra
553 * privileges, because the file is only readable by root.
556 host_private_key = RSA_new();
557 if (load_private_key(HOST_KEY_FILE, "", host_private_key, NULL))
558 host_private_key_loaded = 1;
561 * Get rid of any extra privileges that we may have. We will no
562 * longer need them. Also, extra privileges could make it very hard
563 * to read identity files and other non-world-readable files from the
564 * user's home directory if it happens to be on a NFS volume where
565 * root is mapped to nobody.
569 * Note that some legacy systems need to postpone the following call
570 * to permanently_set_uid() until the private hostkey is destroyed
571 * with RSA_free(). Otherwise the calling user could ptrace() the
572 * process, read the private hostkey and impersonate the host.
573 * OpenBSD does not allow ptracing of setuid processes.
575 permanently_set_uid(original_real_uid);
578 * Now that we are back to our own permissions, create ~/.ssh
579 * directory if it doesn\'t already exist.
581 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_DIR);
582 if (stat(buf, &st) < 0)
583 if (mkdir(buf, 0755) < 0)
584 error("Could not create directory '%.200s'.", buf);
586 /* Check if the connection failed, and try "rsh" if appropriate. */
588 if (options.port != 0)
589 log("Secure connection to %.100s on port %hu refused%.100s.",
591 options.fallback_to_rsh ? "; reverting to insecure method" : "");
593 log("Secure connection to %.100s refused%.100s.", host,
594 options.fallback_to_rsh ? "; reverting to insecure method" : "");
596 if (options.fallback_to_rsh) {
597 rsh_connect(host, options.user, &command);
598 fatal("rsh_connect returned");
602 /* Expand ~ in options.identity_files. */
603 for (i = 0; i < options.num_identity_files; i++)
604 options.identity_files[i] =
605 tilde_expand_filename(options.identity_files[i], original_real_uid);
607 /* Expand ~ in known host file names. */
608 options.system_hostfile = tilde_expand_filename(options.system_hostfile,
610 options.user_hostfile = tilde_expand_filename(options.user_hostfile,
613 /* Log into the remote system. This never returns if the login fails. */
614 ssh_login(host_private_key_loaded, host_private_key,
615 host, (struct sockaddr *)&hostaddr, original_real_uid);
617 /* We no longer need the host private key. Clear it now. */
618 if (host_private_key_loaded)
619 RSA_free(host_private_key); /* Destroys contents safely */
621 /* Close connection cleanly after attack. */
622 cipher_attack_detected = packet_disconnect;
624 /* Enable compression if requested. */
625 if (options.compression) {
626 debug("Requesting compression at level %d.", options.compression_level);
628 if (options.compression_level < 1 || options.compression_level > 9)
629 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
631 /* Send the request. */
632 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
633 packet_put_int(options.compression_level);
636 type = packet_read(&plen);
637 if (type == SSH_SMSG_SUCCESS)
638 packet_start_compression(options.compression_level);
639 else if (type == SSH_SMSG_FAILURE)
640 log("Warning: Remote host refused compression.");
642 packet_disconnect("Protocol error waiting for compression response.");
644 /* Allocate a pseudo tty if appropriate. */
646 debug("Requesting pty.");
648 /* Start the packet. */
649 packet_start(SSH_CMSG_REQUEST_PTY);
651 /* Store TERM in the packet. There is no limit on the
652 length of the string. */
656 packet_put_string(cp, strlen(cp));
658 /* Store window size in the packet. */
659 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
660 memset(&ws, 0, sizeof(ws));
661 packet_put_int(ws.ws_row);
662 packet_put_int(ws.ws_col);
663 packet_put_int(ws.ws_xpixel);
664 packet_put_int(ws.ws_ypixel);
666 /* Store tty modes in the packet. */
667 tty_make_modes(fileno(stdin));
669 /* Send the packet, and wait for it to leave. */
673 /* Read response from the server. */
674 type = packet_read(&plen);
675 if (type == SSH_SMSG_SUCCESS)
677 else if (type == SSH_SMSG_FAILURE)
678 log("Warning: Remote host failed or refused to allocate a pseudo tty.");
680 packet_disconnect("Protocol error waiting for pty request response.");
682 /* Request X11 forwarding if enabled and DISPLAY is set. */
683 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
684 char line[512], proto[512], data[512];
686 int forwarded = 0, got_data = 0, i;
689 /* Try to get Xauthority information for the display. */
690 snprintf(line, sizeof line, "%.100s list %.200s 2>/dev/null",
691 XAUTH_PATH, getenv("DISPLAY"));
692 f = popen(line, "r");
693 if (f && fgets(line, sizeof(line), f) &&
694 sscanf(line, "%*s %s %s", proto, data) == 2)
698 #endif /* XAUTH_PATH */
700 * If we didn't get authentication data, just make up some
701 * data. The forwarding code will check the validity of the
702 * response anyway, and substitute this data. The X11
703 * server, however, will ignore this fake data and use
704 * whatever authentication mechanisms it was using otherwise
705 * for the local connection.
710 strlcpy(proto, "MIT-MAGIC-COOKIE-1", sizeof proto);
711 for (i = 0; i < 16; i++) {
714 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x", rand & 0xff);
719 * Got local authentication reasonable information. Request
720 * forwarding with authentication spoofing.
722 debug("Requesting X11 forwarding with authentication spoofing.");
723 x11_request_forwarding_with_spoofing(proto, data);
725 /* Read response from the server. */
726 type = packet_read(&plen);
727 if (type == SSH_SMSG_SUCCESS) {
730 } else if (type == SSH_SMSG_FAILURE)
731 log("Warning: Remote host denied X11 forwarding.");
733 packet_disconnect("Protocol error waiting for X11 forwarding");
735 /* Tell the packet module whether this is an interactive session. */
736 packet_set_interactive(interactive, options.keepalives);
738 /* Clear agent forwarding if we don\'t have an agent. */
739 authfd = ssh_get_authentication_socket();
741 options.forward_agent = 0;
743 ssh_close_authentication_socket(authfd);
745 /* Request authentication agent forwarding if appropriate. */
746 if (options.forward_agent) {
747 debug("Requesting authentication agent forwarding.");
748 auth_request_forwarding();
750 /* Read response from the server. */
751 type = packet_read(&plen);
752 packet_integrity_check(plen, 0, type);
753 if (type != SSH_SMSG_SUCCESS)
754 log("Warning: Remote host denied authentication agent forwarding.");
756 /* Initiate local TCP/IP port forwardings. */
757 for (i = 0; i < options.num_local_forwards; i++) {
758 debug("Connections to local port %d forwarded to remote address %.200s:%d",
759 options.local_forwards[i].port,
760 options.local_forwards[i].host,
761 options.local_forwards[i].host_port);
762 channel_request_local_forwarding(options.local_forwards[i].port,
763 options.local_forwards[i].host,
764 options.local_forwards[i].host_port,
765 options.gateway_ports);
768 /* Initiate remote TCP/IP port forwardings. */
769 for (i = 0; i < options.num_remote_forwards; i++) {
770 debug("Connections to remote port %d forwarded to local address %.200s:%d",
771 options.remote_forwards[i].port,
772 options.remote_forwards[i].host,
773 options.remote_forwards[i].host_port);
774 channel_request_remote_forwarding(options.remote_forwards[i].port,
775 options.remote_forwards[i].host,
776 options.remote_forwards[i].host_port);
779 /* If requested, let ssh continue in the background. */
780 if (fork_after_authentication_flag)
781 if (daemon(1, 1) < 0)
782 fatal("daemon() failed: %.200s", strerror(errno));
785 * If a command was specified on the command line, execute the
786 * command now. Otherwise request the server to start a shell.
788 if (buffer_len(&command) > 0) {
789 int len = buffer_len(&command);
792 debug("Sending command: %.*s", len, buffer_ptr(&command));
793 packet_start(SSH_CMSG_EXEC_CMD);
794 packet_put_string(buffer_ptr(&command), buffer_len(&command));
798 debug("Requesting shell.");
799 packet_start(SSH_CMSG_EXEC_SHELL);
804 /* Enter the interactive session. */
805 exit_status = client_loop(tty_flag, tty_flag ? options.escape_char : -1);
807 /* Close the connection to the remote host. */
810 /* Exit with the status returned by the program on the remote side. */