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 debug mode is on. This can be set on the command line. */
36 * Flag indicating that nothing should be read from stdin. This can be set
37 * on the command line.
39 int stdin_null_flag = 0;
42 * Flag indicating that ssh should fork after authentication. This is useful
43 * so that the pasphrase can be entered manually, and then ssh goes to the
46 int fork_after_authentication_flag = 0;
49 * General data structure for command line options and options configurable
50 * in configuration files. See readconf.h.
55 * Name of the host we are connecting to. This is the name given on the
56 * command line, or the HostName specified for the user-supplied name in a
61 /* socket address the host resolves to */
62 struct sockaddr_in hostaddr;
65 * Flag to indicate that we have received a window change signal which has
66 * not yet been processed. This will cause a message indicating the new
67 * window size to be sent to the server a little later. This is volatile
68 * because this is updated in a signal handler.
70 volatile int received_window_change_signal = 0;
72 /* Value of argv[0] (set in the main program). */
75 /* Flag indicating whether we have a valid host private key loaded. */
76 int host_private_key_loaded = 0;
78 /* Host private key. */
79 RSA *host_private_key = NULL;
81 /* Original real UID. */
82 uid_t original_real_uid;
84 /* Prints a help message to the user. This function never returns. */
89 fprintf(stderr, "Usage: %s [options] host [command]\n", av0);
90 fprintf(stderr, "Options:\n");
91 fprintf(stderr, " -l user Log in using this user name.\n");
92 fprintf(stderr, " -n Redirect input from /dev/null.\n");
93 fprintf(stderr, " -a Disable authentication agent forwarding.\n");
95 fprintf(stderr, " -k Disable Kerberos ticket and AFS token forwarding.\n");
97 fprintf(stderr, " -x Disable X11 connection forwarding.\n");
98 fprintf(stderr, " -i file Identity for RSA authentication (default: ~/.ssh/identity).\n");
99 fprintf(stderr, " -t Tty; allocate a tty even if command is given.\n");
100 fprintf(stderr, " -v Verbose; display verbose debugging messages.\n");
101 fprintf(stderr, " -V Display version number only.\n");
102 fprintf(stderr, " -P Don't allocate a privileged port.\n");
103 fprintf(stderr, " -q Quiet; don't display any warning messages.\n");
104 fprintf(stderr, " -f Fork into background after authentication.\n");
105 fprintf(stderr, " -e char Set escape character; ``none'' = disable (default: ~).\n");
107 fprintf(stderr, " -c cipher Select encryption algorithm: "
110 fprintf(stderr, " -p port Connect to this port. Server must be on the same port.\n");
111 fprintf(stderr, " -L listen-port:host:port Forward local port to remote address\n");
112 fprintf(stderr, " -R listen-port:host:port Forward remote port to local address\n");
113 fprintf(stderr, " These cause %s to listen for connections on a port, and\n", av0);
114 fprintf(stderr, " forward them to the other side by connecting to host:port.\n");
115 fprintf(stderr, " -C Enable compression.\n");
116 fprintf(stderr, " -g Allow remote hosts to connect to forwarded ports.\n");
117 fprintf(stderr, " -o 'option' Process the option as if it was read from a configuration file.\n");
122 * Connects to the given host using rsh (or prints an error message and exits
123 * if rsh is not available). This function never returns.
126 rsh_connect(char *host, char *user, Buffer * command)
131 log("Using rsh. WARNING: Connection will not be encrypted.");
132 /* Build argument list for rsh. */
134 args[i++] = _PATH_RSH;
135 /* host may have to come after user on some systems */
141 if (buffer_len(command) > 0) {
142 buffer_append(command, "\0", 1);
143 args[i++] = buffer_ptr(command);
147 for (i = 0; args[i]; i++) {
149 fprintf(stderr, " ");
150 fprintf(stderr, "%s", args[i]);
152 fprintf(stderr, "\n");
154 execv(_PATH_RSH, args);
160 * Main program for the ssh client.
163 main(int ac, char **av)
165 int i, opt, optind, type, exit_status, ok, authfd;
166 u_short fwd_port, fwd_host_port;
167 char *optarg, *cp, buf[256];
171 struct passwd *pw, pwcopy;
172 int interactive = 0, dummy;
173 uid_t original_effective_uid;
177 * Save the original real uid. It will be needed later (uid-swapping
178 * may clobber the real uid).
180 original_real_uid = getuid();
181 original_effective_uid = geteuid();
183 /* If we are installed setuid root be careful to not drop core. */
184 if (original_real_uid != original_effective_uid) {
186 rlim.rlim_cur = rlim.rlim_max = 0;
187 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
188 fatal("setrlimit failed: %.100s", strerror(errno));
191 * Use uid-swapping to give up root privileges for the duration of
192 * option processing. We will re-instantiate the rights when we are
193 * ready to create the privileged port, and will permanently drop
194 * them when the port has been created (actually, when the connection
195 * has been made, as we may need to create the port several times).
197 temporarily_use_uid(original_real_uid);
200 * Set our umask to something reasonable, as some files are created
201 * with the default umask. This will make them world-readable but
202 * writable only by the owner, which is ok for all files for which we
203 * don't set the modes explicitly.
207 /* Save our own name. */
210 /* Initialize option structure to indicate that no values have been set. */
211 initialize_options(&options);
213 /* Parse command-line arguments. */
216 /* If program name is not one of the standard names, use it as host name. */
217 if (strchr(av0, '/'))
218 cp = strrchr(av0, '/') + 1;
221 if (strcmp(cp, "rsh") != 0 && strcmp(cp, "ssh") != 0 &&
222 strcmp(cp, "rlogin") != 0 && strcmp(cp, "slogin") != 0)
225 for (optind = 1; optind < ac; optind++) {
226 if (av[optind][0] != '-') {
229 if ((cp = strchr(av[optind], '@'))) {
230 options.user = av[optind];
240 if (strchr("eilcpLRo", opt)) { /* options with arguments */
241 optarg = av[optind] + 2;
242 if (strcmp(optarg, "") == 0) {
243 if (optind >= ac - 1)
245 optarg = av[++optind];
258 fork_after_authentication_flag = 1;
263 options.forward_x11 = 0;
267 options.forward_x11 = 1;
271 options.gateway_ports = 1;
275 options.use_privileged_port = 0;
279 options.forward_agent = 0;
283 options.kerberos_tgt_passing = 0;
284 options.afs_token_passing = 0;
288 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;
323 else if (strlen(optarg) == 1)
324 options.escape_char = (unsigned char) optarg[0];
325 else if (strcmp(optarg, "none") == 0)
326 options.escape_char = -2;
328 fprintf(stderr, "Bad escape character '%s'.\n", optarg);
334 options.cipher = cipher_number(optarg);
335 if (options.cipher == -1) {
336 fprintf(stderr, "Unknown cipher type '%s'\n", optarg);
342 options.port = atoi(optarg);
346 options.user = optarg;
350 if (sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
351 &fwd_host_port) != 3) {
352 fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
356 add_remote_forward(&options, fwd_port, buf, fwd_host_port);
360 if (sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
361 &fwd_host_port) != 3) {
362 fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
366 add_local_forward(&options, fwd_port, buf, fwd_host_port);
370 options.compression = 1;
375 if (process_config_line(&options, host ? host : "", optarg,
376 "command-line", 0, &dummy) != 0)
385 /* Check that we got a host name. */
389 /* check if RSA support exists */
390 if (rsa_alive() == 0) {
392 "%s: no RSA support in libssl and libcrypto. See ssl(8).\n",
396 /* Initialize the command to execute on remote host. */
397 buffer_init(&command);
400 * Save the command to execute on the remote host in a buffer. There
401 * is no limit on the length of the command, except by the maximum
402 * packet size. Also sets the tty flag if there is no command.
405 /* No command specified - execute shell on a tty. */
408 /* A command has been specified. Store it into the
410 for (i = optind; i < ac; i++) {
412 buffer_append(&command, " ", 1);
413 buffer_append(&command, av[i], strlen(av[i]));
417 /* Cannot fork to background if no command. */
418 if (fork_after_authentication_flag && buffer_len(&command) == 0)
419 fatal("Cannot fork into background without a command to execute.");
421 /* Allocate a tty by default if no command specified. */
422 if (buffer_len(&command) == 0)
425 /* Do not allocate a tty if stdin is not a tty. */
426 if (!isatty(fileno(stdin))) {
428 fprintf(stderr, "Pseudo-terminal will not be allocated because stdin is not a terminal.\n");
432 pw = getpwuid(original_real_uid);
434 fprintf(stderr, "You don't exist, go away!\n");
437 /* Take a copy of the returned structure. */
438 memset(&pwcopy, 0, sizeof(pwcopy));
439 pwcopy.pw_name = xstrdup(pw->pw_name);
440 pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
441 pwcopy.pw_uid = pw->pw_uid;
442 pwcopy.pw_gid = pw->pw_gid;
443 pwcopy.pw_dir = xstrdup(pw->pw_dir);
444 pwcopy.pw_shell = xstrdup(pw->pw_shell);
447 /* Initialize "log" output. Since we are the client all output
448 actually goes to the terminal. */
449 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0);
451 /* Read per-user configuration file. */
452 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_CONFFILE);
453 read_config_file(buf, host, &options);
455 /* Read systemwide configuration file. */
456 read_config_file(HOST_CONFIG_FILE, host, &options);
458 /* Fill configuration defaults. */
459 fill_default_options(&options);
462 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0);
464 if (options.user == NULL)
465 options.user = xstrdup(pw->pw_name);
467 if (options.hostname != NULL)
468 host = options.hostname;
470 /* Find canonic host name. */
471 if (strchr(host, '.') == 0) {
472 struct hostent *hp = gethostbyname(host);
474 if (strchr(hp->h_name, '.') != 0)
475 host = xstrdup(hp->h_name);
476 else if (hp->h_aliases != 0
477 && hp->h_aliases[0] != 0
478 && strchr(hp->h_aliases[0], '.') != 0)
479 host = xstrdup(hp->h_aliases[0]);
482 /* Disable rhosts authentication if not running as root. */
483 if (original_effective_uid != 0 || !options.use_privileged_port) {
484 options.rhosts_authentication = 0;
485 options.rhosts_rsa_authentication = 0;
488 * If using rsh has been selected, exec it now (without trying
489 * anything else). Note that we must release privileges first.
491 if (options.use_rsh) {
493 * Restore our superuser privileges. This must be done
494 * before permanently setting the uid.
498 /* Switch to the original uid permanently. */
499 permanently_set_uid(original_real_uid);
502 rsh_connect(host, options.user, &command);
503 fatal("rsh_connect returned");
505 /* Restore our superuser privileges. */
509 * Open a connection to the remote host. This needs root privileges
510 * if rhosts_{rsa_}authentication is enabled.
513 ok = ssh_connect(host, &hostaddr, options.port,
514 options.connection_attempts,
515 !options.rhosts_authentication &&
516 !options.rhosts_rsa_authentication,
518 options.proxy_command);
521 * If we successfully made the connection, load the host private key
522 * in case we will need it later for combined rsa-rhosts
523 * authentication. This must be done before releasing extra
524 * privileges, because the file is only readable by root.
527 host_private_key = RSA_new();
528 if (load_private_key(HOST_KEY_FILE, "", host_private_key, NULL))
529 host_private_key_loaded = 1;
532 * Get rid of any extra privileges that we may have. We will no
533 * longer need them. Also, extra privileges could make it very hard
534 * to read identity files and other non-world-readable files from the
535 * user's home directory if it happens to be on a NFS volume where
536 * root is mapped to nobody.
540 * Note that some legacy systems need to postpone the following call
541 * to permanently_set_uid() until the private hostkey is destroyed
542 * with RSA_free(). Otherwise the calling user could ptrace() the
543 * process, read the private hostkey and impersonate the host.
544 * OpenBSD does not allow ptracing of setuid processes.
546 permanently_set_uid(original_real_uid);
549 * Now that we are back to our own permissions, create ~/.ssh
550 * directory if it doesn\'t already exist.
552 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_DIR);
553 if (stat(buf, &st) < 0)
554 if (mkdir(buf, 0755) < 0)
555 error("Could not create directory '%.200s'.", buf);
557 /* Check if the connection failed, and try "rsh" if appropriate. */
559 if (options.port != 0)
560 log("Secure connection to %.100s on port %hu refused%.100s.",
562 options.fallback_to_rsh ? "; reverting to insecure method" : "");
564 log("Secure connection to %.100s refused%.100s.", host,
565 options.fallback_to_rsh ? "; reverting to insecure method" : "");
567 if (options.fallback_to_rsh) {
568 rsh_connect(host, options.user, &command);
569 fatal("rsh_connect returned");
573 /* Expand ~ in options.identity_files. */
574 for (i = 0; i < options.num_identity_files; i++)
575 options.identity_files[i] =
576 tilde_expand_filename(options.identity_files[i], original_real_uid);
578 /* Expand ~ in known host file names. */
579 options.system_hostfile = tilde_expand_filename(options.system_hostfile,
581 options.user_hostfile = tilde_expand_filename(options.user_hostfile,
584 /* Log into the remote system. This never returns if the login fails. */
585 ssh_login(host_private_key_loaded, host_private_key,
586 host, &hostaddr, original_real_uid);
588 /* We no longer need the host private key. Clear it now. */
589 if (host_private_key_loaded)
590 RSA_free(host_private_key); /* Destroys contents safely */
592 /* Close connection cleanly after attack. */
593 cipher_attack_detected = packet_disconnect;
595 /* Enable compression if requested. */
596 if (options.compression) {
597 debug("Requesting compression at level %d.", options.compression_level);
599 if (options.compression_level < 1 || options.compression_level > 9)
600 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
602 /* Send the request. */
603 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
604 packet_put_int(options.compression_level);
607 type = packet_read(&plen);
608 if (type == SSH_SMSG_SUCCESS)
609 packet_start_compression(options.compression_level);
610 else if (type == SSH_SMSG_FAILURE)
611 log("Warning: Remote host refused compression.");
613 packet_disconnect("Protocol error waiting for compression response.");
615 /* Allocate a pseudo tty if appropriate. */
617 debug("Requesting pty.");
619 /* Start the packet. */
620 packet_start(SSH_CMSG_REQUEST_PTY);
622 /* Store TERM in the packet. There is no limit on the
623 length of the string. */
627 packet_put_string(cp, strlen(cp));
629 /* Store window size in the packet. */
630 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
631 memset(&ws, 0, sizeof(ws));
632 packet_put_int(ws.ws_row);
633 packet_put_int(ws.ws_col);
634 packet_put_int(ws.ws_xpixel);
635 packet_put_int(ws.ws_ypixel);
637 /* Store tty modes in the packet. */
638 tty_make_modes(fileno(stdin));
640 /* Send the packet, and wait for it to leave. */
644 /* Read response from the server. */
645 type = packet_read(&plen);
646 if (type == SSH_SMSG_SUCCESS)
648 else if (type == SSH_SMSG_FAILURE)
649 log("Warning: Remote host failed or refused to allocate a pseudo tty.");
651 packet_disconnect("Protocol error waiting for pty request response.");
653 /* Request X11 forwarding if enabled and DISPLAY is set. */
654 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
655 char line[512], proto[512], data[512];
657 int forwarded = 0, got_data = 0, i;
660 /* Try to get Xauthority information for the display. */
661 snprintf(line, sizeof line, "%.100s list %.200s 2>/dev/null",
662 XAUTH_PATH, getenv("DISPLAY"));
663 f = popen(line, "r");
664 if (f && fgets(line, sizeof(line), f) &&
665 sscanf(line, "%*s %s %s", proto, data) == 2)
669 #endif /* XAUTH_PATH */
671 * If we didn't get authentication data, just make up some
672 * data. The forwarding code will check the validity of the
673 * response anyway, and substitute this data. The X11
674 * server, however, will ignore this fake data and use
675 * whatever authentication mechanisms it was using otherwise
676 * for the local connection.
681 strlcpy(proto, "MIT-MAGIC-COOKIE-1", sizeof proto);
682 for (i = 0; i < 16; i++) {
685 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x", rand & 0xff);
690 * Got local authentication reasonable information. Request
691 * forwarding with authentication spoofing.
693 debug("Requesting X11 forwarding with authentication spoofing.");
694 x11_request_forwarding_with_spoofing(proto, data);
696 /* Read response from the server. */
697 type = packet_read(&plen);
698 if (type == SSH_SMSG_SUCCESS) {
701 } else if (type == SSH_SMSG_FAILURE)
702 log("Warning: Remote host denied X11 forwarding.");
704 packet_disconnect("Protocol error waiting for X11 forwarding");
706 /* Tell the packet module whether this is an interactive session. */
707 packet_set_interactive(interactive, options.keepalives);
709 /* Clear agent forwarding if we don\'t have an agent. */
710 authfd = ssh_get_authentication_socket();
712 options.forward_agent = 0;
714 ssh_close_authentication_socket(authfd);
716 /* Request authentication agent forwarding if appropriate. */
717 if (options.forward_agent) {
718 debug("Requesting authentication agent forwarding.");
719 auth_request_forwarding();
721 /* Read response from the server. */
722 type = packet_read(&plen);
723 packet_integrity_check(plen, 0, type);
724 if (type != SSH_SMSG_SUCCESS)
725 log("Warning: Remote host denied authentication agent forwarding.");
727 /* Initiate local TCP/IP port forwardings. */
728 for (i = 0; i < options.num_local_forwards; i++) {
729 debug("Connections to local port %d forwarded to remote address %.200s:%d",
730 options.local_forwards[i].port,
731 options.local_forwards[i].host,
732 options.local_forwards[i].host_port);
733 channel_request_local_forwarding(options.local_forwards[i].port,
734 options.local_forwards[i].host,
735 options.local_forwards[i].host_port,
736 options.gateway_ports);
739 /* Initiate remote TCP/IP port forwardings. */
740 for (i = 0; i < options.num_remote_forwards; i++) {
741 debug("Connections to remote port %d forwarded to local address %.200s:%d",
742 options.remote_forwards[i].port,
743 options.remote_forwards[i].host,
744 options.remote_forwards[i].host_port);
745 channel_request_remote_forwarding(options.remote_forwards[i].port,
746 options.remote_forwards[i].host,
747 options.remote_forwards[i].host_port);
750 /* If requested, let ssh continue in the background. */
751 if (fork_after_authentication_flag)
752 if (daemon(1, 1) < 0)
753 fatal("daemon() failed: %.200s", strerror(errno));
756 * If a command was specified on the command line, execute the
757 * command now. Otherwise request the server to start a shell.
759 if (buffer_len(&command) > 0) {
760 int len = buffer_len(&command);
763 debug("Sending command: %.*s", len, buffer_ptr(&command));
764 packet_start(SSH_CMSG_EXEC_CMD);
765 packet_put_string(buffer_ptr(&command), buffer_len(&command));
769 debug("Requesting shell.");
770 packet_start(SSH_CMSG_EXEC_SHELL);
775 /* Enter the interactive session. */
776 exit_status = client_loop(tty_flag, tty_flag ? options.escape_char : -1);
778 /* Close the connection to the remote host. */
781 /* Exit with the status returned by the program on the remote side. */