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, " -i file Identity for RSA authentication (default: ~/.ssh/identity).\n");
107 fprintf(stderr, " -t Tty; allocate a tty even if command is given.\n");
108 fprintf(stderr, " -v Verbose; display verbose debugging messages.\n");
109 fprintf(stderr, " -V Display version number only.\n");
110 fprintf(stderr, " -P Don't allocate a privileged port.\n");
111 fprintf(stderr, " -q Quiet; don't display any warning messages.\n");
112 fprintf(stderr, " -f Fork into background after authentication.\n");
113 fprintf(stderr, " -e char Set escape character; ``none'' = disable (default: ~).\n");
115 fprintf(stderr, " -c cipher Select encryption algorithm: "
118 fprintf(stderr, " -p port Connect to this port. Server must be on the same port.\n");
119 fprintf(stderr, " -L listen-port:host:port Forward local port to remote address\n");
120 fprintf(stderr, " -R listen-port:host:port Forward remote port to local address\n");
121 fprintf(stderr, " These cause %s to listen for connections on a port, and\n", av0);
122 fprintf(stderr, " forward them to the other side by connecting to host:port.\n");
123 fprintf(stderr, " -C Enable compression.\n");
124 fprintf(stderr, " -g Allow remote hosts to connect to forwarded ports.\n");
125 fprintf(stderr, " -4 Use IPv4 only.\n");
126 fprintf(stderr, " -6 Use IPv6 only.\n");
127 fprintf(stderr, " -o 'option' Process the option as if it was read from a configuration file.\n");
132 * Connects to the given host using rsh (or prints an error message and exits
133 * if rsh is not available). This function never returns.
136 rsh_connect(char *host, char *user, Buffer * command)
141 log("Using rsh. WARNING: Connection will not be encrypted.");
142 /* Build argument list for rsh. */
144 args[i++] = _PATH_RSH;
145 /* host may have to come after user on some systems */
151 if (buffer_len(command) > 0) {
152 buffer_append(command, "\0", 1);
153 args[i++] = buffer_ptr(command);
157 for (i = 0; args[i]; i++) {
159 fprintf(stderr, " ");
160 fprintf(stderr, "%s", args[i]);
162 fprintf(stderr, "\n");
164 execv(_PATH_RSH, args);
170 * Main program for the ssh client.
173 main(int ac, char **av)
175 int i, opt, optind, type, exit_status, ok, authfd;
176 u_short fwd_port, fwd_host_port;
177 char *optarg, *cp, buf[256];
181 struct passwd *pw, pwcopy;
182 int interactive = 0, dummy;
183 uid_t original_effective_uid;
187 * Save the original real uid. It will be needed later (uid-swapping
188 * may clobber the real uid).
190 original_real_uid = getuid();
191 original_effective_uid = geteuid();
193 /* If we are installed setuid root be careful to not drop core. */
194 if (original_real_uid != original_effective_uid) {
196 rlim.rlim_cur = rlim.rlim_max = 0;
197 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
198 fatal("setrlimit failed: %.100s", strerror(errno));
201 * Use uid-swapping to give up root privileges for the duration of
202 * option processing. We will re-instantiate the rights when we are
203 * ready to create the privileged port, and will permanently drop
204 * them when the port has been created (actually, when the connection
205 * has been made, as we may need to create the port several times).
207 temporarily_use_uid(original_real_uid);
210 * Set our umask to something reasonable, as some files are created
211 * with the default umask. This will make them world-readable but
212 * writable only by the owner, which is ok for all files for which we
213 * don't set the modes explicitly.
217 /* Save our own name. */
220 /* Initialize option structure to indicate that no values have been set. */
221 initialize_options(&options);
223 /* Parse command-line arguments. */
226 /* If program name is not one of the standard names, use it as host name. */
227 if (strchr(av0, '/'))
228 cp = strrchr(av0, '/') + 1;
231 if (strcmp(cp, "rsh") != 0 && strcmp(cp, "ssh") != 0 &&
232 strcmp(cp, "rlogin") != 0 && strcmp(cp, "slogin") != 0)
235 for (optind = 1; optind < ac; optind++) {
236 if (av[optind][0] != '-') {
239 if ((cp = strchr(av[optind], '@'))) {
242 options.user = av[optind];
252 if (strchr("eilcpLRo", opt)) { /* options with arguments */
253 optarg = av[optind] + 2;
254 if (strcmp(optarg, "") == 0) {
255 if (optind >= ac - 1)
257 optarg = av[++optind];
278 fork_after_authentication_flag = 1;
283 options.forward_x11 = 0;
287 options.forward_x11 = 1;
291 options.gateway_ports = 1;
295 options.use_privileged_port = 0;
299 options.forward_agent = 0;
303 options.kerberos_tgt_passing = 0;
304 options.afs_token_passing = 0;
308 if (stat(optarg, &st) < 0) {
309 fprintf(stderr, "Warning: Identity file %s does not exist.\n",
313 if (options.num_identity_files >= SSH_MAX_IDENTITY_FILES)
314 fatal("Too many identity files specified (max %d)",
315 SSH_MAX_IDENTITY_FILES);
316 options.identity_files[options.num_identity_files++] =
326 fprintf(stderr, "SSH Version %s, protocol version %d.%d.\n",
327 SSH_VERSION, PROTOCOL_MAJOR, PROTOCOL_MINOR);
329 fprintf(stderr, "Compiled with SSL.\n");
331 fprintf(stderr, "Compiled with SSL (RSAref version).\n");
336 options.log_level = SYSLOG_LEVEL_DEBUG;
340 options.log_level = SYSLOG_LEVEL_QUIET;
344 if (optarg[0] == '^' && optarg[2] == 0 &&
345 (unsigned char) optarg[1] >= 64 && (unsigned char) optarg[1] < 128)
346 options.escape_char = (unsigned char) optarg[1] & 31;
347 else if (strlen(optarg) == 1)
348 options.escape_char = (unsigned char) optarg[0];
349 else if (strcmp(optarg, "none") == 0)
350 options.escape_char = -2;
352 fprintf(stderr, "Bad escape character '%s'.\n", optarg);
358 options.cipher = cipher_number(optarg);
359 if (options.cipher == -1) {
360 fprintf(stderr, "Unknown cipher type '%s'\n", optarg);
366 options.port = atoi(optarg);
370 options.user = optarg;
374 if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf,
375 &fwd_host_port) != 3 &&
376 sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
377 &fwd_host_port) != 3) {
378 fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
382 add_remote_forward(&options, fwd_port, buf, fwd_host_port);
386 if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf,
387 &fwd_host_port) != 3 &&
388 sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
389 &fwd_host_port) != 3) {
390 fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
394 add_local_forward(&options, fwd_port, buf, fwd_host_port);
398 options.compression = 1;
403 if (process_config_line(&options, host ? host : "", optarg,
404 "command-line", 0, &dummy) != 0)
413 /* Check that we got a host name. */
417 /* check if RSA support exists */
418 if (rsa_alive() == 0) {
420 "%s: no RSA support in libssl and libcrypto. See ssl(8).\n",
424 /* Initialize the command to execute on remote host. */
425 buffer_init(&command);
428 * Save the command to execute on the remote host in a buffer. There
429 * is no limit on the length of the command, except by the maximum
430 * packet size. Also sets the tty flag if there is no command.
433 /* No command specified - execute shell on a tty. */
436 /* A command has been specified. Store it into the
438 for (i = optind; i < ac; i++) {
440 buffer_append(&command, " ", 1);
441 buffer_append(&command, av[i], strlen(av[i]));
445 /* Cannot fork to background if no command. */
446 if (fork_after_authentication_flag && buffer_len(&command) == 0)
447 fatal("Cannot fork into background without a command to execute.");
449 /* Allocate a tty by default if no command specified. */
450 if (buffer_len(&command) == 0)
453 /* Do not allocate a tty if stdin is not a tty. */
454 if (!isatty(fileno(stdin))) {
456 fprintf(stderr, "Pseudo-terminal will not be allocated because stdin is not a terminal.\n");
460 pw = getpwuid(original_real_uid);
462 fprintf(stderr, "You don't exist, go away!\n");
465 /* Take a copy of the returned structure. */
466 memset(&pwcopy, 0, sizeof(pwcopy));
467 pwcopy.pw_name = xstrdup(pw->pw_name);
468 pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
469 pwcopy.pw_uid = pw->pw_uid;
470 pwcopy.pw_gid = pw->pw_gid;
471 pwcopy.pw_dir = xstrdup(pw->pw_dir);
472 pwcopy.pw_shell = xstrdup(pw->pw_shell);
475 /* Initialize "log" output. Since we are the client all output
476 actually goes to the terminal. */
477 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0);
479 /* Read per-user configuration file. */
480 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_CONFFILE);
481 read_config_file(buf, host, &options);
483 /* Read systemwide configuration file. */
484 read_config_file(HOST_CONFIG_FILE, host, &options);
486 /* Fill configuration defaults. */
487 fill_default_options(&options);
490 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0);
492 if (options.user == NULL)
493 options.user = xstrdup(pw->pw_name);
495 if (options.hostname != NULL)
496 host = options.hostname;
498 /* Find canonic host name. */
499 if (strchr(host, '.') == 0) {
500 struct addrinfo hints;
501 struct addrinfo *ai = NULL;
503 memset(&hints, 0, sizeof(hints));
504 hints.ai_family = AF_UNSPEC;
505 hints.ai_flags = AI_CANONNAME;
506 hints.ai_socktype = SOCK_STREAM;
507 errgai = getaddrinfo(host, NULL, &hints, &ai);
509 if (ai->ai_canonname != NULL)
510 host = xstrdup(ai->ai_canonname);
514 /* Disable rhosts authentication if not running as root. */
515 if (original_effective_uid != 0 || !options.use_privileged_port) {
516 options.rhosts_authentication = 0;
517 options.rhosts_rsa_authentication = 0;
520 * If using rsh has been selected, exec it now (without trying
521 * anything else). Note that we must release privileges first.
523 if (options.use_rsh) {
525 * Restore our superuser privileges. This must be done
526 * before permanently setting the uid.
530 /* Switch to the original uid permanently. */
531 permanently_set_uid(original_real_uid);
534 rsh_connect(host, options.user, &command);
535 fatal("rsh_connect returned");
537 /* Restore our superuser privileges. */
541 * Open a connection to the remote host. This needs root privileges
542 * if rhosts_{rsa_}authentication is enabled.
545 ok = ssh_connect(host, &hostaddr, options.port,
546 options.connection_attempts,
547 !options.rhosts_authentication &&
548 !options.rhosts_rsa_authentication,
550 options.proxy_command);
553 * If we successfully made the connection, load the host private key
554 * in case we will need it later for combined rsa-rhosts
555 * authentication. This must be done before releasing extra
556 * privileges, because the file is only readable by root.
559 host_private_key = RSA_new();
560 if (load_private_key(HOST_KEY_FILE, "", host_private_key, NULL))
561 host_private_key_loaded = 1;
564 * Get rid of any extra privileges that we may have. We will no
565 * longer need them. Also, extra privileges could make it very hard
566 * to read identity files and other non-world-readable files from the
567 * user's home directory if it happens to be on a NFS volume where
568 * root is mapped to nobody.
572 * Note that some legacy systems need to postpone the following call
573 * to permanently_set_uid() until the private hostkey is destroyed
574 * with RSA_free(). Otherwise the calling user could ptrace() the
575 * process, read the private hostkey and impersonate the host.
576 * OpenBSD does not allow ptracing of setuid processes.
578 permanently_set_uid(original_real_uid);
581 * Now that we are back to our own permissions, create ~/.ssh
582 * directory if it doesn\'t already exist.
584 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_DIR);
585 if (stat(buf, &st) < 0)
586 if (mkdir(buf, 0755) < 0)
587 error("Could not create directory '%.200s'.", buf);
589 /* Check if the connection failed, and try "rsh" if appropriate. */
591 if (options.port != 0)
592 log("Secure connection to %.100s on port %hu refused%.100s.",
594 options.fallback_to_rsh ? "; reverting to insecure method" : "");
596 log("Secure connection to %.100s refused%.100s.", host,
597 options.fallback_to_rsh ? "; reverting to insecure method" : "");
599 if (options.fallback_to_rsh) {
600 rsh_connect(host, options.user, &command);
601 fatal("rsh_connect returned");
605 /* Expand ~ in options.identity_files. */
606 for (i = 0; i < options.num_identity_files; i++)
607 options.identity_files[i] =
608 tilde_expand_filename(options.identity_files[i], original_real_uid);
610 /* Expand ~ in known host file names. */
611 options.system_hostfile = tilde_expand_filename(options.system_hostfile,
613 options.user_hostfile = tilde_expand_filename(options.user_hostfile,
616 /* Log into the remote system. This never returns if the login fails. */
617 ssh_login(host_private_key_loaded, host_private_key,
618 host, (struct sockaddr *)&hostaddr, original_real_uid);
620 /* We no longer need the host private key. Clear it now. */
621 if (host_private_key_loaded)
622 RSA_free(host_private_key); /* Destroys contents safely */
624 /* Close connection cleanly after attack. */
625 cipher_attack_detected = packet_disconnect;
627 /* Enable compression if requested. */
628 if (options.compression) {
629 debug("Requesting compression at level %d.", options.compression_level);
631 if (options.compression_level < 1 || options.compression_level > 9)
632 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
634 /* Send the request. */
635 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
636 packet_put_int(options.compression_level);
639 type = packet_read(&plen);
640 if (type == SSH_SMSG_SUCCESS)
641 packet_start_compression(options.compression_level);
642 else if (type == SSH_SMSG_FAILURE)
643 log("Warning: Remote host refused compression.");
645 packet_disconnect("Protocol error waiting for compression response.");
647 /* Allocate a pseudo tty if appropriate. */
649 debug("Requesting pty.");
651 /* Start the packet. */
652 packet_start(SSH_CMSG_REQUEST_PTY);
654 /* Store TERM in the packet. There is no limit on the
655 length of the string. */
659 packet_put_string(cp, strlen(cp));
661 /* Store window size in the packet. */
662 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
663 memset(&ws, 0, sizeof(ws));
664 packet_put_int(ws.ws_row);
665 packet_put_int(ws.ws_col);
666 packet_put_int(ws.ws_xpixel);
667 packet_put_int(ws.ws_ypixel);
669 /* Store tty modes in the packet. */
670 tty_make_modes(fileno(stdin));
672 /* Send the packet, and wait for it to leave. */
676 /* Read response from the server. */
677 type = packet_read(&plen);
678 if (type == SSH_SMSG_SUCCESS)
680 else if (type == SSH_SMSG_FAILURE)
681 log("Warning: Remote host failed or refused to allocate a pseudo tty.");
683 packet_disconnect("Protocol error waiting for pty request response.");
685 /* Request X11 forwarding if enabled and DISPLAY is set. */
686 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
687 char line[512], proto[512], data[512];
689 int forwarded = 0, got_data = 0, i;
692 /* Try to get Xauthority information for the display. */
693 snprintf(line, sizeof line, "%.100s list %.200s 2>/dev/null",
694 XAUTH_PATH, getenv("DISPLAY"));
695 f = popen(line, "r");
696 if (f && fgets(line, sizeof(line), f) &&
697 sscanf(line, "%*s %s %s", proto, data) == 2)
701 #endif /* XAUTH_PATH */
703 * If we didn't get authentication data, just make up some
704 * data. The forwarding code will check the validity of the
705 * response anyway, and substitute this data. The X11
706 * server, however, will ignore this fake data and use
707 * whatever authentication mechanisms it was using otherwise
708 * for the local connection.
713 strlcpy(proto, "MIT-MAGIC-COOKIE-1", sizeof proto);
714 for (i = 0; i < 16; i++) {
717 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x", rand & 0xff);
722 * Got local authentication reasonable information. Request
723 * forwarding with authentication spoofing.
725 debug("Requesting X11 forwarding with authentication spoofing.");
726 x11_request_forwarding_with_spoofing(proto, data);
728 /* Read response from the server. */
729 type = packet_read(&plen);
730 if (type == SSH_SMSG_SUCCESS) {
733 } else if (type == SSH_SMSG_FAILURE)
734 log("Warning: Remote host denied X11 forwarding.");
736 packet_disconnect("Protocol error waiting for X11 forwarding");
738 /* Tell the packet module whether this is an interactive session. */
739 packet_set_interactive(interactive, options.keepalives);
741 /* Clear agent forwarding if we don\'t have an agent. */
742 authfd = ssh_get_authentication_socket();
744 options.forward_agent = 0;
746 ssh_close_authentication_socket(authfd);
748 /* Request authentication agent forwarding if appropriate. */
749 if (options.forward_agent) {
750 debug("Requesting authentication agent forwarding.");
751 auth_request_forwarding();
753 /* Read response from the server. */
754 type = packet_read(&plen);
755 packet_integrity_check(plen, 0, type);
756 if (type != SSH_SMSG_SUCCESS)
757 log("Warning: Remote host denied authentication agent forwarding.");
759 /* Initiate local TCP/IP port forwardings. */
760 for (i = 0; i < options.num_local_forwards; i++) {
761 debug("Connections to local port %d forwarded to remote address %.200s:%d",
762 options.local_forwards[i].port,
763 options.local_forwards[i].host,
764 options.local_forwards[i].host_port);
765 channel_request_local_forwarding(options.local_forwards[i].port,
766 options.local_forwards[i].host,
767 options.local_forwards[i].host_port,
768 options.gateway_ports);
771 /* Initiate remote TCP/IP port forwardings. */
772 for (i = 0; i < options.num_remote_forwards; i++) {
773 debug("Connections to remote port %d forwarded to local address %.200s:%d",
774 options.remote_forwards[i].port,
775 options.remote_forwards[i].host,
776 options.remote_forwards[i].host_port);
777 channel_request_remote_forwarding(options.remote_forwards[i].port,
778 options.remote_forwards[i].host,
779 options.remote_forwards[i].host_port);
782 /* If requested, let ssh continue in the background. */
783 if (fork_after_authentication_flag)
784 if (daemon(1, 1) < 0)
785 fatal("daemon() failed: %.200s", strerror(errno));
788 * If a command was specified on the command line, execute the
789 * command now. Otherwise request the server to start a shell.
791 if (buffer_len(&command) > 0) {
792 int len = buffer_len(&command);
795 debug("Sending command: %.*s", len, buffer_ptr(&command));
796 packet_start(SSH_CMSG_EXEC_CMD);
797 packet_put_string(buffer_ptr(&command), buffer_len(&command));
801 debug("Requesting shell.");
802 packet_start(SSH_CMSG_EXEC_SHELL);
807 /* Enter the interactive session. */
808 exit_status = client_loop(tty_flag, tty_flag ? options.escape_char : -1);
810 /* Close the connection to the remote host. */
813 /* Exit with the status returned by the program on the remote side. */