5 Author: Tatu Ylonen <ylo@cs.hut.fi>
7 Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
10 Created: Sat Mar 18 16:36:11 1995 ylo
12 Ssh client program. This program can be used to log into a remote machine.
13 The software supports strong authentication, encryption, and forwarding
14 of X11, TCP/IP, and authentication connections.
16 Modified to work with SSL by Niels Provos <provos@citi.umich.edu> in Canada.
31 /* Flag indicating whether debug mode is on. This can be set on the
35 /* Flag indicating whether to allocate a pseudo tty. This can be set on the
36 command line, and is automatically set if no command is given on the command
40 /* Flag indicating that nothing should be read from stdin. This can be set
41 on the command line. */
42 int stdin_null_flag = 0;
44 /* Flag indicating that ssh should fork after authentication. This is useful
45 so that the pasphrase can be entered manually, and then ssh goes to the
47 int fork_after_authentication_flag = 0;
49 /* General data structure for command line options and options configurable
50 in configuration files. See readconf.h. */
53 /* Name of the host we are connecting to. This is the name given on the
54 command line, or the HostName specified for the user-supplied name
55 in a configuration file. */
58 /* socket address the host resolves to */
59 struct sockaddr_in hostaddr;
61 /* Flag to indicate that we have received a window change signal which has
62 not yet been processed. This will cause a message indicating the new
63 window size to be sent to the server a little later. This is volatile
64 because this is updated in a signal handler. */
65 volatile int received_window_change_signal = 0;
67 /* Value of argv[0] (set in the main program). */
70 /* Flag indicating whether we have a valid host private key loaded. */
71 int host_private_key_loaded = 0;
73 /* Host private key. */
74 RSA *host_private_key = NULL;
76 /* Original real UID. */
77 uid_t original_real_uid;
79 /* Prints a help message to the user. This function never returns. */
84 fprintf(stderr, "Usage: %s [options] host [command]\n", av0);
85 fprintf(stderr, "Options:\n");
86 fprintf(stderr, " -l user Log in using this user name.\n");
87 fprintf(stderr, " -n Redirect input from /dev/null.\n");
88 fprintf(stderr, " -a Disable authentication agent forwarding.\n");
90 fprintf(stderr, " -k Disable Kerberos ticket and AFS token forwarding.\n");
92 fprintf(stderr, " -x Disable X11 connection forwarding.\n");
93 fprintf(stderr, " -i file Identity for RSA authentication (default: ~/.ssh/identity).\n");
94 fprintf(stderr, " -t Tty; allocate a tty even if command is given.\n");
95 fprintf(stderr, " -v Verbose; display verbose debugging messages.\n");
96 fprintf(stderr, " -V Display version number only.\n");
97 fprintf(stderr, " -P Don't allocate a privileged port.\n");
98 fprintf(stderr, " -q Quiet; don't display any warning messages.\n");
99 fprintf(stderr, " -f Fork into background after authentication.\n");
100 fprintf(stderr, " -e char Set escape character; ``none'' = disable (default: ~).\n");
102 fprintf(stderr, " -c cipher Select encryption algorithm: "
105 fprintf(stderr, " -p port Connect to this port. Server must be on the same port.\n");
106 fprintf(stderr, " -L listen-port:host:port Forward local port to remote address\n");
107 fprintf(stderr, " -R listen-port:host:port Forward remote port to local address\n");
108 fprintf(stderr, " These cause %s to listen for connections on a port, and\n", av0);
109 fprintf(stderr, " forward them to the other side by connecting to host:port.\n");
110 fprintf(stderr, " -C Enable compression.\n");
111 fprintf(stderr, " -g Allow remote hosts to connect to forwarded ports.\n");
112 fprintf(stderr, " -o 'option' Process the option as if it was read from a configuration file.\n");
116 /* Connects to the given host using rsh (or prints an error message and exits
117 if rsh is not available). This function never returns. */
120 rsh_connect(char *host, char *user, Buffer *command)
125 log("Using rsh. WARNING: Connection will not be encrypted.");
126 /* Build argument list for rsh. */
128 args[i++] = _PATH_RSH;
129 args[i++] = host; /* may have to come after user on some systems */
135 if (buffer_len(command) > 0)
137 buffer_append(command, "\0", 1);
138 args[i++] = buffer_ptr(command);
143 for (i = 0; args[i]; i++)
146 fprintf(stderr, " ");
147 fprintf(stderr, "%s", args[i]);
149 fprintf(stderr, "\n");
151 execv(_PATH_RSH, args);
156 /* Main program for the ssh client. */
159 main(int ac, char **av)
161 int i, opt, optind, type, exit_status, ok, fwd_port, fwd_host_port, authfd;
162 char *optarg, *cp, buf[256];
166 struct passwd *pw, pwcopy;
167 int interactive = 0, dummy;
168 uid_t original_effective_uid;
171 /* Save the original real uid. It will be needed later (uid-swapping may
172 clobber the real uid). */
173 original_real_uid = getuid();
174 original_effective_uid = geteuid();
176 /* If we are installed setuid root be careful to not drop core. */
177 if (original_real_uid != original_effective_uid)
180 rlim.rlim_cur = rlim.rlim_max = 0;
181 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
182 fatal("setrlimit failed: %.100s", strerror(errno));
185 /* Use uid-swapping to give up root privileges for the duration of option
186 processing. We will re-instantiate the rights when we are ready to
187 create the privileged port, and will permanently drop them when the
188 port has been created (actually, when the connection has been made, as
189 we may need to create the port several times). */
190 temporarily_use_uid(original_real_uid);
192 /* Set our umask to something reasonable, as some files are created with
193 the default umask. This will make them world-readable but writable
194 only by the owner, which is ok for all files for which we don't set
195 the modes explicitly. */
198 /* Save our own name. */
201 /* Initialize option structure to indicate that no values have been set. */
202 initialize_options(&options);
204 /* Parse command-line arguments. */
207 /* If program name is not one of the standard names, use it as host name. */
208 if (strchr(av0, '/'))
209 cp = strrchr(av0, '/') + 1;
212 if (strcmp(cp, "rsh") != 0 && strcmp(cp, "ssh") != 0 &&
213 strcmp(cp, "rlogin") != 0 && strcmp(cp, "slogin") != 0)
216 for (optind = 1; optind < ac; optind++)
218 if (av[optind][0] != '-')
222 if ((cp = strchr(av[optind], '@'))) {
223 options.user = av[optind];
234 if (strchr("eilcpLRo", opt)) /* options with arguments */
236 optarg = av[optind] + 2;
237 if (strcmp(optarg, "") == 0)
239 if (optind >= ac - 1)
241 optarg = av[++optind];
257 fork_after_authentication_flag = 1;
262 options.forward_x11 = 0;
266 options.forward_x11 = 1;
270 options.gateway_ports = 1;
274 options.use_privileged_port = 0;
278 options.forward_agent = 0;
282 options.kerberos_tgt_passing = 0;
283 options.afs_token_passing = 0;
287 if (stat(optarg, &st) < 0)
289 fprintf(stderr, "Warning: Identity file %s does not exist.\n",
293 if (options.num_identity_files >= SSH_MAX_IDENTITY_FILES)
294 fatal("Too many identity files specified (max %d)",
295 SSH_MAX_IDENTITY_FILES);
296 options.identity_files[options.num_identity_files++] =
306 fprintf(stderr, "SSH Version %s, protocol version %d.%d.\n",
307 SSH_VERSION, PROTOCOL_MAJOR, PROTOCOL_MINOR);
308 fprintf(stderr, "Compiled with SSL.\n");
312 options.log_level = SYSLOG_LEVEL_DEBUG;
316 options.log_level = SYSLOG_LEVEL_QUIET;
320 if (optarg[0] == '^' && optarg[2] == 0 &&
321 (unsigned char)optarg[1] >= 64 && (unsigned char)optarg[1] < 128)
322 options.escape_char = (unsigned char)optarg[1] & 31;
324 if (strlen(optarg) == 1)
325 options.escape_char = (unsigned char)optarg[0];
327 if (strcmp(optarg, "none") == 0)
328 options.escape_char = -2;
331 fprintf(stderr, "Bad escape character '%s'.\n", optarg);
337 options.cipher = cipher_number(optarg);
338 if (options.cipher == -1)
340 fprintf(stderr, "Unknown cipher type '%s'\n", optarg);
346 options.port = atoi(optarg);
347 if (options.port < 1 || options.port > 65535)
349 fprintf(stderr, "Bad port %s.\n", optarg);
355 options.user = optarg;
359 if (sscanf(optarg, "%d:%255[^:]:%d", &fwd_port, buf,
360 &fwd_host_port) != 3)
362 fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
366 add_remote_forward(&options, fwd_port, buf, fwd_host_port);
370 if (sscanf(optarg, "%d:%255[^:]:%d", &fwd_port, buf,
371 &fwd_host_port) != 3)
373 fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
377 add_local_forward(&options, fwd_port, buf, fwd_host_port);
381 options.compression = 1;
386 process_config_line(&options, host ? host : "", optarg,
387 "command-line", 0, &dummy);
395 /* Check that we got a host name. */
399 /* check if RSA support exists */
400 if (rsa_alive() == 0) {
401 extern char *__progname;
404 "%s: no RSA support in libssl and libcrypto. See ssl(8).\n",
409 /* Initialize the command to execute on remote host. */
410 buffer_init(&command);
412 /* Save the command to execute on the remote host in a buffer. There is
413 no limit on the length of the command, except by the maximum packet
414 size. Also sets the tty flag if there is no command. */
417 /* No command specified - execute shell on a tty. */
422 /* A command has been specified. Store it into the buffer. */
423 for (i = optind; i < ac; i++)
426 buffer_append(&command, " ", 1);
427 buffer_append(&command, av[i], strlen(av[i]));
431 /* Cannot fork to background if no command. */
432 if (fork_after_authentication_flag && buffer_len(&command) == 0)
433 fatal("Cannot fork into background without a command to execute.");
435 /* Allocate a tty by default if no command specified. */
436 if (buffer_len(&command) == 0)
439 /* Do not allocate a tty if stdin is not a tty. */
440 if (!isatty(fileno(stdin)))
443 fprintf(stderr, "Pseudo-terminal will not be allocated because stdin is not a terminal.\n");
448 pw = getpwuid(original_real_uid);
451 fprintf(stderr, "You don't exist, go away!\n");
455 /* Take a copy of the returned structure. */
456 memset(&pwcopy, 0, sizeof(pwcopy));
457 pwcopy.pw_name = xstrdup(pw->pw_name);
458 pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
459 pwcopy.pw_uid = pw->pw_uid;
460 pwcopy.pw_gid = pw->pw_gid;
461 pwcopy.pw_dir = xstrdup(pw->pw_dir);
462 pwcopy.pw_shell = xstrdup(pw->pw_shell);
465 /* Initialize "log" output. Since we are the client all output actually
466 goes to the terminal. */
467 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0);
469 /* Read per-user configuration file. */
470 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_CONFFILE);
471 read_config_file(buf, host, &options);
473 /* Read systemwide configuration file. */
474 read_config_file(HOST_CONFIG_FILE, host, &options);
476 /* Fill configuration defaults. */
477 fill_default_options(&options);
480 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0);
482 if (options.user == NULL)
483 options.user = xstrdup(pw->pw_name);
485 if (options.hostname != NULL)
486 host = options.hostname;
488 /* Find canonic host name. */
489 if (strchr(host, '.') == 0)
491 struct hostent *hp = gethostbyname(host);
494 if (strchr(hp->h_name, '.') != 0)
495 host = xstrdup(hp->h_name);
496 else if (hp->h_aliases != 0
497 && hp->h_aliases[0] != 0
498 && strchr(hp->h_aliases[0], '.') != 0)
499 host = xstrdup(hp->h_aliases[0]);
503 /* Disable rhosts authentication if not running as root. */
504 if (original_effective_uid != 0 || !options.use_privileged_port)
506 options.rhosts_authentication = 0;
507 options.rhosts_rsa_authentication = 0;
510 /* If using rsh has been selected, exec it now (without trying anything
511 else). Note that we must release privileges first. */
514 /* Restore our superuser privileges. This must be done before
515 permanently setting the uid. */
518 /* Switch to the original uid permanently. */
519 permanently_set_uid(original_real_uid);
522 rsh_connect(host, options.user, &command);
523 fatal("rsh_connect returned");
526 /* Restore our superuser privileges. */
529 /* Open a connection to the remote host. This needs root privileges if
530 rhosts_{rsa_}authentication is enabled. */
532 ok = ssh_connect(host, &hostaddr, options.port, options.connection_attempts,
533 !options.rhosts_authentication &&
534 !options.rhosts_rsa_authentication,
535 original_real_uid, options.proxy_command);
537 /* If we successfully made the connection, load the host private key in
538 case we will need it later for combined rsa-rhosts authentication.
539 This must be done before releasing extra privileges, because the file
540 is only readable by root. */
543 host_private_key = RSA_new();
544 if (load_private_key(HOST_KEY_FILE, "", host_private_key, NULL))
545 host_private_key_loaded = 1;
548 /* Get rid of any extra privileges that we may have. We will no longer need
549 them. Also, extra privileges could make it very hard to read identity
550 files and other non-world-readable files from the user's home directory
551 if it happens to be on a NFS volume where root is mapped to nobody. */
552 permanently_set_uid(original_real_uid);
554 /* Now that we are back to our own permissions, create ~/.ssh directory
555 if it doesn\'t already exist. */
556 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_DIR);
557 if (stat(buf, &st) < 0)
558 if (mkdir(buf, 0755) < 0)
559 error("Could not create directory '%.200s'.", buf);
561 /* Check if the connection failed, and try "rsh" if appropriate. */
564 if (options.port != 0)
565 log("Secure connection to %.100s on port %d refused%.100s.",
567 options.fallback_to_rsh ? "; reverting to insecure method" : "");
569 log("Secure connection to %.100s refused%.100s.", host,
570 options.fallback_to_rsh ? "; reverting to insecure method" : "");
572 if (options.fallback_to_rsh)
574 rsh_connect(host, options.user, &command);
575 fatal("rsh_connect returned");
580 /* Expand ~ in options.identity_files. */
581 for (i = 0; i < options.num_identity_files; i++)
582 options.identity_files[i] =
583 tilde_expand_filename(options.identity_files[i], original_real_uid);
585 /* Expand ~ in known host file names. */
586 options.system_hostfile = tilde_expand_filename(options.system_hostfile,
588 options.user_hostfile = tilde_expand_filename(options.user_hostfile,
591 /* Log into the remote system. This never returns if the login fails. */
592 ssh_login(host_private_key_loaded, host_private_key,
593 host, &hostaddr, original_real_uid);
595 /* We no longer need the host private key. Clear it now. */
596 if (host_private_key_loaded)
597 RSA_free(host_private_key); /* Destroys contents safely */
599 /* Close connection cleanly after attack. */
600 cipher_attack_detected = packet_disconnect;
602 /* If requested, fork and let ssh continue in the background. */
603 if (fork_after_authentication_flag)
607 fatal("fork failed: %.100s", strerror(errno));
613 /* Enable compression if requested. */
614 if (options.compression)
616 debug("Requesting compression at level %d.", options.compression_level);
618 if (options.compression_level < 1 || options.compression_level > 9)
619 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
621 /* Send the request. */
622 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
623 packet_put_int(options.compression_level);
626 type = packet_read(&plen);
627 if (type == SSH_SMSG_SUCCESS)
628 packet_start_compression(options.compression_level);
629 else if (type == SSH_SMSG_FAILURE)
630 log("Warning: Remote host refused compression.");
632 packet_disconnect("Protocol error waiting for compression response.");
635 /* Allocate a pseudo tty if appropriate. */
638 debug("Requesting pty.");
640 /* Start the packet. */
641 packet_start(SSH_CMSG_REQUEST_PTY);
643 /* Store TERM in the packet. There is no limit on the length of the
648 packet_put_string(cp, strlen(cp));
650 /* Store window size in the packet. */
651 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
652 memset(&ws, 0, sizeof(ws));
653 packet_put_int(ws.ws_row);
654 packet_put_int(ws.ws_col);
655 packet_put_int(ws.ws_xpixel);
656 packet_put_int(ws.ws_ypixel);
658 /* Store tty modes in the packet. */
659 tty_make_modes(fileno(stdin));
661 /* Send the packet, and wait for it to leave. */
665 /* Read response from the server. */
666 type = packet_read(&plen);
667 if (type == SSH_SMSG_SUCCESS)
669 else if (type == SSH_SMSG_FAILURE)
670 log("Warning: Remote host failed or refused to allocate a pseudo tty.");
672 packet_disconnect("Protocol error waiting for pty request response.");
675 /* Request X11 forwarding if enabled and DISPLAY is set. */
676 if (options.forward_x11 && getenv("DISPLAY") != NULL)
678 char line[512], proto[512], data[512];
680 int forwarded = 0, got_data = 0, i;
683 /* Try to get Xauthority information for the display. */
684 snprintf(line, sizeof line, "%.100s list %.200s 2>/dev/null",
685 XAUTH_PATH, getenv("DISPLAY"));
686 f = popen(line, "r");
687 if (f && fgets(line, sizeof(line), f) &&
688 sscanf(line, "%*s %s %s", proto, data) == 2)
692 #endif /* XAUTH_PATH */
693 /* If we didn't get authentication data, just make up some data. The
694 forwarding code will check the validity of the response anyway, and
695 substitute this data. The X11 server, however, will ignore this
696 fake data and use whatever authentication mechanisms it was using
697 otherwise for the local connection. */
702 strlcpy(proto, "MIT-MAGIC-COOKIE-1", sizeof proto);
703 for (i = 0; i < 16; i++) {
706 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x", rand & 0xff);
711 /* Got local authentication reasonable information. Request forwarding
712 with authentication spoofing. */
713 debug("Requesting X11 forwarding with authentication spoofing.");
714 x11_request_forwarding_with_spoofing(proto, data);
716 /* Read response from the server. */
717 type = packet_read(&plen);
718 if (type == SSH_SMSG_SUCCESS)
723 else if (type == SSH_SMSG_FAILURE)
724 log("Warning: Remote host denied X11 forwarding.");
726 packet_disconnect("Protocol error waiting for X11 forwarding");
729 /* Tell the packet module whether this is an interactive session. */
730 packet_set_interactive(interactive, options.keepalives);
732 /* Clear agent forwarding if we don\'t have an agent. */
733 authfd = ssh_get_authentication_socket();
735 options.forward_agent = 0;
737 ssh_close_authentication_socket(authfd);
739 /* Request authentication agent forwarding if appropriate. */
740 if (options.forward_agent)
742 debug("Requesting authentication agent forwarding.");
743 auth_request_forwarding();
745 /* Read response from the server. */
746 type = packet_read(&plen);
747 packet_integrity_check(plen, 0, type);
748 if (type != SSH_SMSG_SUCCESS)
749 log("Warning: Remote host denied authentication agent forwarding.");
752 /* Initiate local TCP/IP port forwardings. */
753 for (i = 0; i < options.num_local_forwards; i++)
755 debug("Connections to local port %d forwarded to remote address %.200s:%d",
756 options.local_forwards[i].port, options.local_forwards[i].host,
757 options.local_forwards[i].host_port);
758 channel_request_local_forwarding(options.local_forwards[i].port,
759 options.local_forwards[i].host,
760 options.local_forwards[i].host_port);
763 /* Initiate remote TCP/IP port forwardings. */
764 for (i = 0; i < options.num_remote_forwards; i++)
766 debug("Connections to remote port %d forwarded to local address %.200s:%d",
767 options.remote_forwards[i].port, options.remote_forwards[i].host,
768 options.remote_forwards[i].host_port);
769 channel_request_remote_forwarding(options.remote_forwards[i].port,
770 options.remote_forwards[i].host,
771 options.remote_forwards[i].host_port);
774 /* If a command was specified on the command line, execute the command now.
775 Otherwise request the server to start a shell. */
776 if (buffer_len(&command) > 0)
778 int len = buffer_len(&command);
781 debug("Sending command: %.*s", len, buffer_ptr(&command));
782 packet_start(SSH_CMSG_EXEC_CMD);
783 packet_put_string(buffer_ptr(&command), buffer_len(&command));
789 debug("Requesting shell.");
790 packet_start(SSH_CMSG_EXEC_SHELL);
795 /* Enter the interactive session. */
796 exit_status = client_loop(tty_flag, tty_flag ? options.escape_char : -1);
798 /* Close the connection to the remote host. */
801 /* Exit with the status returned by the program on the remote side. */