2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * Ssh client program. This program can be used to log into a remote machine.
6 * The software supports strong authentication, encryption, and forwarding
7 * of X11, TCP/IP, and authentication connections.
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
15 * Copyright (c) 1999 Niels Provos. All rights reserved.
16 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
18 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
19 * in Canada (German citizen).
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 RCSID("$OpenBSD: ssh.c,v 1.224 2004/07/28 09:40:29 markus Exp $");
45 #include <openssl/evp.h>
46 #include <openssl/err.h>
61 #include "pathnames.h"
63 #include "clientloop.h"
66 #include "sshconnect.h"
73 #include "monitor_fdpass.h"
80 extern char *__progname;
82 /* Flag indicating whether debug mode is on. This can be set on the command line. */
85 /* Flag indicating whether a tty should be allocated */
88 int force_tty_flag = 0;
90 /* don't exec a shell */
91 int no_shell_flag = 0;
94 * Flag indicating that nothing should be read from stdin. This can be set
95 * on the command line.
97 int stdin_null_flag = 0;
100 * Flag indicating that ssh should fork after authentication. This is useful
101 * so that the passphrase can be entered manually, and then ssh goes to the
104 int fork_after_authentication_flag = 0;
107 * General data structure for command line options and options configurable
108 * in configuration files. See readconf.h.
112 /* optional user configfile */
116 * Name of the host we are connecting to. This is the name given on the
117 * command line, or the HostName specified for the user-supplied name in a
118 * configuration file.
122 /* socket address the host resolves to */
123 struct sockaddr_storage hostaddr;
125 /* Private host keys. */
126 Sensitive sensitive_data;
128 /* Original real UID. */
129 uid_t original_real_uid;
130 uid_t original_effective_uid;
132 /* command to be executed */
135 /* Should we execute a command or invoke a subsystem? */
136 int subsystem_flag = 0;
138 /* # of replies received for global requests */
139 static int client_global_request_id = 0;
141 /* pid of proxycommand child process */
142 pid_t proxy_command_pid = 0;
144 /* fd to control socket */
147 /* Only used in control client mode */
148 volatile sig_atomic_t control_client_terminate = 0;
149 u_int control_server_pid = 0;
151 /* Prints a help message to the user. This function never returns. */
157 "usage: ssh [-1246AaCfghkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
158 " [-D port] [-e escape_char] [-F configfile] [-i identity_file]\n"
159 " [-L port:host:hostport] [-l login_name] [-m mac_spec] [-o option]\n"
160 " [-p port] [-R port:host:hostport] [-S ctl] [user@]hostname [command]\n"
165 static int ssh_session(void);
166 static int ssh_session2(void);
167 static void load_public_identity_files(void);
168 static void control_client(const char *path);
171 * Main program for the ssh client.
174 main(int ac, char **av)
176 int i, opt, exit_status;
177 u_short fwd_port, fwd_host_port;
178 char sfwd_port[6], sfwd_host_port[6];
179 char *p, *cp, *line, buf[256];
183 extern int optind, optreset;
186 __progname = ssh_get_progname(av[0]);
191 * Save the original real uid. It will be needed later (uid-swapping
192 * may clobber the real uid).
194 original_real_uid = getuid();
195 original_effective_uid = geteuid();
198 * Use uid-swapping to give up root privileges for the duration of
199 * option processing. We will re-instantiate the rights when we are
200 * ready to create the privileged port, and will permanently drop
201 * them when the port has been created (actually, when the connection
202 * has been made, as we may need to create the port several times).
206 #ifdef HAVE_SETRLIMIT
207 /* If we are installed setuid root be careful to not drop core. */
208 if (original_real_uid != original_effective_uid) {
210 rlim.rlim_cur = rlim.rlim_max = 0;
211 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
212 fatal("setrlimit failed: %.100s", strerror(errno));
216 pw = getpwuid(original_real_uid);
218 logit("You don't exist, go away!");
221 /* Take a copy of the returned structure. */
225 * Set our umask to something reasonable, as some files are created
226 * with the default umask. This will make them world-readable but
227 * writable only by the owner, which is ok for all files for which we
228 * don't set the modes explicitly.
232 /* Initialize option structure to indicate that no values have been set. */
233 initialize_options(&options);
235 /* Parse command-line arguments. */
239 while ((opt = getopt(ac, av,
240 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNPR:S:TVXY")) != -1) {
243 options.protocol = SSH_PROTO_1;
246 options.protocol = SSH_PROTO_2;
249 options.address_family = AF_INET;
252 options.address_family = AF_INET6;
258 fork_after_authentication_flag = 1;
262 options.forward_x11 = 0;
265 options.forward_x11 = 1;
268 options.forward_x11 = 1;
269 options.forward_x11_trusted = 1;
272 options.gateway_ports = 1;
274 case 'P': /* deprecated */
275 options.use_privileged_port = 0;
278 options.forward_agent = 0;
281 options.forward_agent = 1;
284 options.gss_deleg_creds = 0;
287 if (stat(optarg, &st) < 0) {
288 fprintf(stderr, "Warning: Identity file %s "
289 "does not exist.\n", optarg);
292 if (options.num_identity_files >=
293 SSH_MAX_IDENTITY_FILES)
294 fatal("Too many identity files specified "
295 "(max %d)", SSH_MAX_IDENTITY_FILES);
296 options.identity_files[options.num_identity_files++] =
301 options.smartcard_device = xstrdup(optarg);
303 fprintf(stderr, "no support for smartcards.\n");
312 if (debug_flag == 0) {
314 options.log_level = SYSLOG_LEVEL_DEBUG1;
316 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
322 fprintf(stderr, "%s, %s\n",
323 SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
328 options.log_level = SYSLOG_LEVEL_QUIET;
331 if (optarg[0] == '^' && optarg[2] == 0 &&
332 (u_char) optarg[1] >= 64 &&
333 (u_char) optarg[1] < 128)
334 options.escape_char = (u_char) optarg[1] & 31;
335 else if (strlen(optarg) == 1)
336 options.escape_char = (u_char) optarg[0];
337 else if (strcmp(optarg, "none") == 0)
338 options.escape_char = SSH_ESCAPECHAR_NONE;
340 fprintf(stderr, "Bad escape character '%s'.\n",
346 if (ciphers_valid(optarg)) {
348 options.ciphers = xstrdup(optarg);
349 options.cipher = SSH_CIPHER_INVALID;
352 options.cipher = cipher_number(optarg);
353 if (options.cipher == -1) {
355 "Unknown cipher type '%s'\n",
359 if (options.cipher == SSH_CIPHER_3DES)
360 options.ciphers = "3des-cbc";
361 else if (options.cipher == SSH_CIPHER_BLOWFISH)
362 options.ciphers = "blowfish-cbc";
364 options.ciphers = (char *)-1;
368 if (mac_valid(optarg))
369 options.macs = xstrdup(optarg);
371 fprintf(stderr, "Unknown mac type '%s'\n",
377 options.control_master =
378 (options.control_master >= 1) ? 2 : 1;
381 options.port = a2port(optarg);
382 if (options.port == 0) {
383 fprintf(stderr, "Bad port '%s'\n", optarg);
388 options.user = optarg;
393 if (sscanf(optarg, "%5[0123456789]:%255[^:]:%5[0123456789]",
394 sfwd_port, buf, sfwd_host_port) != 3 &&
395 sscanf(optarg, "%5[0123456789]/%255[^/]/%5[0123456789]",
396 sfwd_port, buf, sfwd_host_port) != 3) {
398 "Bad forwarding specification '%s'\n",
403 if ((fwd_port = a2port(sfwd_port)) == 0 ||
404 (fwd_host_port = a2port(sfwd_host_port)) == 0) {
406 "Bad forwarding port(s) '%s'\n", optarg);
410 add_local_forward(&options, fwd_port, buf,
413 add_remote_forward(&options, fwd_port, buf,
418 fwd_port = a2port(optarg);
420 fprintf(stderr, "Bad dynamic port '%s'\n",
424 add_local_forward(&options, fwd_port, "socks", 0);
428 options.compression = 1;
439 line = xstrdup(optarg);
440 if (process_config_line(&options, host ? host : "",
441 line, "command-line", 0, &dummy) != 0)
449 if (options.control_path != NULL)
450 free(options.control_path);
451 options.control_path = xstrdup(optarg);
454 options.bind_address = optarg;
467 if (ac > 0 && !host && **av != '-') {
468 if (strrchr(*av, '@')) {
470 cp = strrchr(p, '@');
471 if (cp == NULL || cp == p)
479 optind = optreset = 1;
485 /* Check that we got a host name. */
489 SSLeay_add_all_algorithms();
490 ERR_load_crypto_strings();
492 /* Initialize the command to execute on remote host. */
493 buffer_init(&command);
496 * Save the command to execute on the remote host in a buffer. There
497 * is no limit on the length of the command, except by the maximum
498 * packet size. Also sets the tty flag if there is no command.
501 /* No command specified - execute shell on a tty. */
503 if (subsystem_flag) {
505 "You must specify a subsystem to invoke.\n");
509 /* A command has been specified. Store it into the buffer. */
510 for (i = 0; i < ac; i++) {
512 buffer_append(&command, " ", 1);
513 buffer_append(&command, av[i], strlen(av[i]));
517 /* Cannot fork to background if no command. */
518 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
519 fatal("Cannot fork into background without a command to execute.");
521 /* Allocate a tty by default if no command specified. */
522 if (buffer_len(&command) == 0)
528 /* Do not allocate a tty if stdin is not a tty. */
529 if (!isatty(fileno(stdin)) && !force_tty_flag) {
531 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
536 * Initialize "log" output. Since we are the client all output
537 * actually goes to stderr.
539 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
540 SYSLOG_FACILITY_USER, 1);
543 * Read per-user configuration file. Ignore the system wide config
544 * file if the user specifies a config file on the command line.
546 if (config != NULL) {
547 if (!read_config_file(config, host, &options, 0))
548 fatal("Can't open user config file %.100s: "
549 "%.100s", config, strerror(errno));
552 * Since the config file parsing code aborts if it sees
553 * options it doesn't recognize, allow users to put
554 * options specific to compile-time add-ons in alternate
555 * config files so their primary config file will
556 * interoperate SSH versions that don't support those
560 snprintf(buf, sizeof buf, "%.100s/%.100s.gssapi", pw->pw_dir,
561 _PATH_SSH_USER_CONFFILE);
562 (void)read_config_file(buf, host, &options, 1);
564 snprintf(buf, sizeof buf, "%.100s/%.100s.gsi", pw->pw_dir,
565 _PATH_SSH_USER_CONFFILE);
566 (void)read_config_file(buf, host, &options, 1);
569 snprintf(buf, sizeof buf, "%.100s/%.100s.krb", pw->pw_dir,
570 _PATH_SSH_USER_CONFFILE);
571 (void)read_config_file(buf, host, &options, 1);
574 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
575 _PATH_SSH_USER_CONFFILE);
576 (void)read_config_file(buf, host, &options, 1);
578 /* Read systemwide configuration file after use config. */
579 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
583 /* Fill configuration defaults. */
584 fill_default_options(&options);
586 channel_set_af(options.address_family);
589 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
593 if (options.user == NULL) {
594 options.user = xstrdup(pw->pw_name);
595 options.implicit = 1;
597 else options.implicit = 0;
599 if (options.hostname != NULL)
600 host = options.hostname;
602 /* force lowercase for hostkey matching */
603 if (options.host_key_alias != NULL) {
604 for (p = options.host_key_alias; *p; p++)
609 if (options.proxy_command != NULL &&
610 strcmp(options.proxy_command, "none") == 0)
611 options.proxy_command = NULL;
613 if (options.control_path != NULL) {
614 options.control_path = tilde_expand_filename(
615 options.control_path, original_real_uid);
617 if (options.control_path != NULL && options.control_master == 0)
618 control_client(options.control_path); /* This doesn't return */
620 /* Open a connection to the remote host. */
621 if (ssh_connect(host, &hostaddr, options.port,
622 options.address_family, options.connection_attempts,
624 options.use_privileged_port,
626 original_effective_uid == 0 && options.use_privileged_port,
628 options.proxy_command) != 0)
632 * If we successfully made the connection, load the host private key
633 * in case we will need it later for combined rsa-rhosts
634 * authentication. This must be done before releasing extra
635 * privileges, because the file is only readable by root.
636 * If we cannot access the private keys, load the public keys
637 * instead and try to execute the ssh-keysign helper instead.
639 sensitive_data.nkeys = 0;
640 sensitive_data.keys = NULL;
641 sensitive_data.external_keysign = 0;
642 if (options.rhosts_rsa_authentication ||
643 options.hostbased_authentication) {
644 sensitive_data.nkeys = 3;
645 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
649 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
650 _PATH_HOST_KEY_FILE, "", NULL);
651 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
652 _PATH_HOST_DSA_KEY_FILE, "", NULL);
653 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
654 _PATH_HOST_RSA_KEY_FILE, "", NULL);
657 if (options.hostbased_authentication == 1 &&
658 sensitive_data.keys[0] == NULL &&
659 sensitive_data.keys[1] == NULL &&
660 sensitive_data.keys[2] == NULL) {
661 sensitive_data.keys[1] = key_load_public(
662 _PATH_HOST_DSA_KEY_FILE, NULL);
663 sensitive_data.keys[2] = key_load_public(
664 _PATH_HOST_RSA_KEY_FILE, NULL);
665 sensitive_data.external_keysign = 1;
669 * Get rid of any extra privileges that we may have. We will no
670 * longer need them. Also, extra privileges could make it very hard
671 * to read identity files and other non-world-readable files from the
672 * user's home directory if it happens to be on a NFS volume where
673 * root is mapped to nobody.
675 if (original_effective_uid == 0) {
677 permanently_set_uid(pw);
681 * Now that we are back to our own permissions, create ~/.ssh
682 * directory if it doesn\'t already exist.
684 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
685 if (stat(buf, &st) < 0)
686 if (mkdir(buf, 0700) < 0)
687 error("Could not create directory '%.200s'.", buf);
689 /* load options.identity_files */
690 load_public_identity_files();
692 /* Expand ~ in known host file names. */
694 options.system_hostfile =
695 tilde_expand_filename(options.system_hostfile, original_real_uid);
696 options.user_hostfile =
697 tilde_expand_filename(options.user_hostfile, original_real_uid);
698 options.system_hostfile2 =
699 tilde_expand_filename(options.system_hostfile2, original_real_uid);
700 options.user_hostfile2 =
701 tilde_expand_filename(options.user_hostfile2, original_real_uid);
703 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
705 /* Log into the remote system. This never returns if the login fails. */
706 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
708 /* We no longer need the private host keys. Clear them now. */
709 if (sensitive_data.nkeys != 0) {
710 for (i = 0; i < sensitive_data.nkeys; i++) {
711 if (sensitive_data.keys[i] != NULL) {
712 /* Destroys contents safely */
713 debug3("clear hostkey %d", i);
714 key_free(sensitive_data.keys[i]);
715 sensitive_data.keys[i] = NULL;
718 xfree(sensitive_data.keys);
720 for (i = 0; i < options.num_identity_files; i++) {
721 if (options.identity_files[i]) {
722 xfree(options.identity_files[i]);
723 options.identity_files[i] = NULL;
725 if (options.identity_keys[i]) {
726 key_free(options.identity_keys[i]);
727 options.identity_keys[i] = NULL;
731 exit_status = compat20 ? ssh_session2() : ssh_session();
734 if (options.control_path != NULL && control_fd != -1)
735 unlink(options.control_path);
738 * Send SIGHUP to proxy command if used. We don't wait() in
739 * case it hangs and instead rely on init to reap the child
741 if (proxy_command_pid > 1)
742 kill(proxy_command_pid, SIGHUP);
747 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
750 x11_get_proto(char **_proto, char **_data)
755 static char proto[512], data[512];
757 int got_data = 0, generated = 0, do_unlink = 0, i;
758 char *display, *xauthdir, *xauthfile;
761 xauthdir = xauthfile = NULL;
764 proto[0] = data[0] = '\0';
766 if (!options.xauth_location ||
767 (stat(options.xauth_location, &st) == -1)) {
768 debug("No xauth program.");
770 if ((display = getenv("DISPLAY")) == NULL) {
771 debug("x11_get_proto: DISPLAY not set");
775 * Handle FamilyLocal case where $DISPLAY does
776 * not match an authorization entry. For this we
777 * just try "xauth list unix:displaynum.screennum".
778 * XXX: "localhost" match to determine FamilyLocal
781 if (strncmp(display, "localhost:", 10) == 0) {
782 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
786 if (options.forward_x11_trusted == 0) {
787 xauthdir = xmalloc(MAXPATHLEN);
788 xauthfile = xmalloc(MAXPATHLEN);
789 strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
790 if (mkdtemp(xauthdir) != NULL) {
792 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
794 snprintf(cmd, sizeof(cmd),
795 "%s -f %s generate %s " SSH_X11_PROTO
796 " untrusted timeout 1200 2>" _PATH_DEVNULL,
797 options.xauth_location, xauthfile, display);
798 debug2("x11_get_proto: %s", cmd);
799 if (system(cmd) == 0)
803 snprintf(cmd, sizeof(cmd),
804 "%s %s%s list %s . 2>" _PATH_DEVNULL,
805 options.xauth_location,
806 generated ? "-f " : "" ,
807 generated ? xauthfile : "",
809 debug2("x11_get_proto: %s", cmd);
811 if (f && fgets(line, sizeof(line), f) &&
812 sscanf(line, "%*s %511s %511s", proto, data) == 2)
828 * If we didn't get authentication data, just make up some
829 * data. The forwarding code will check the validity of the
830 * response anyway, and substitute this data. The X11
831 * server, however, will ignore this fake data and use
832 * whatever authentication mechanisms it was using otherwise
833 * for the local connection.
838 logit("Warning: No xauth data; "
839 "using fake authentication data for X11 forwarding.");
840 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
841 for (i = 0; i < 16; i++) {
844 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
852 ssh_init_forwarding(void)
857 /* Initiate local TCP/IP port forwardings. */
858 for (i = 0; i < options.num_local_forwards; i++) {
859 debug("Connections to local port %d forwarded to remote address %.200s:%d",
860 options.local_forwards[i].port,
861 options.local_forwards[i].host,
862 options.local_forwards[i].host_port);
863 success += channel_setup_local_fwd_listener(
864 options.local_forwards[i].port,
865 options.local_forwards[i].host,
866 options.local_forwards[i].host_port,
867 options.gateway_ports);
869 if (i > 0 && success == 0)
870 error("Could not request local forwarding.");
872 /* Initiate remote TCP/IP port forwardings. */
873 for (i = 0; i < options.num_remote_forwards; i++) {
874 debug("Connections to remote port %d forwarded to local address %.200s:%d",
875 options.remote_forwards[i].port,
876 options.remote_forwards[i].host,
877 options.remote_forwards[i].host_port);
878 channel_request_remote_forwarding(
879 options.remote_forwards[i].port,
880 options.remote_forwards[i].host,
881 options.remote_forwards[i].host_port);
886 check_agent_present(void)
888 if (options.forward_agent) {
889 /* Clear agent forwarding if we don\'t have an agent. */
890 if (!ssh_agent_present())
891 options.forward_agent = 0;
904 /* Enable compression if requested. */
905 if (options.compression) {
906 debug("Requesting compression at level %d.", options.compression_level);
908 if (options.compression_level < 1 || options.compression_level > 9)
909 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
911 /* Send the request. */
912 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
913 packet_put_int(options.compression_level);
916 type = packet_read();
917 if (type == SSH_SMSG_SUCCESS)
918 packet_start_compression(options.compression_level);
919 else if (type == SSH_SMSG_FAILURE)
920 logit("Warning: Remote host refused compression.");
922 packet_disconnect("Protocol error waiting for compression response.");
924 /* Allocate a pseudo tty if appropriate. */
926 debug("Requesting pty.");
928 /* Start the packet. */
929 packet_start(SSH_CMSG_REQUEST_PTY);
931 /* Store TERM in the packet. There is no limit on the
932 length of the string. */
936 packet_put_cstring(cp);
938 /* Store window size in the packet. */
939 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
940 memset(&ws, 0, sizeof(ws));
941 packet_put_int(ws.ws_row);
942 packet_put_int(ws.ws_col);
943 packet_put_int(ws.ws_xpixel);
944 packet_put_int(ws.ws_ypixel);
946 /* Store tty modes in the packet. */
947 tty_make_modes(fileno(stdin), NULL);
949 /* Send the packet, and wait for it to leave. */
953 /* Read response from the server. */
954 type = packet_read();
955 if (type == SSH_SMSG_SUCCESS) {
958 } else if (type == SSH_SMSG_FAILURE)
959 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
961 packet_disconnect("Protocol error waiting for pty request response.");
963 /* Request X11 forwarding if enabled and DISPLAY is set. */
964 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
966 /* Get reasonable local authentication information. */
967 x11_get_proto(&proto, &data);
968 /* Request forwarding with authentication spoofing. */
969 debug("Requesting X11 forwarding with authentication spoofing.");
970 x11_request_forwarding_with_spoofing(0, proto, data);
972 /* Read response from the server. */
973 type = packet_read();
974 if (type == SSH_SMSG_SUCCESS) {
976 } else if (type == SSH_SMSG_FAILURE) {
977 logit("Warning: Remote host denied X11 forwarding.");
979 packet_disconnect("Protocol error waiting for X11 forwarding");
982 /* Tell the packet module whether this is an interactive session. */
983 packet_set_interactive(interactive);
985 /* Request authentication agent forwarding if appropriate. */
986 check_agent_present();
988 if (options.forward_agent) {
989 debug("Requesting authentication agent forwarding.");
990 auth_request_forwarding();
992 /* Read response from the server. */
993 type = packet_read();
995 if (type != SSH_SMSG_SUCCESS)
996 logit("Warning: Remote host denied authentication agent forwarding.");
999 /* Initiate port forwardings. */
1000 ssh_init_forwarding();
1002 /* If requested, let ssh continue in the background. */
1003 if (fork_after_authentication_flag)
1004 if (daemon(1, 1) < 0)
1005 fatal("daemon() failed: %.200s", strerror(errno));
1008 * If a command was specified on the command line, execute the
1009 * command now. Otherwise request the server to start a shell.
1011 if (buffer_len(&command) > 0) {
1012 int len = buffer_len(&command);
1015 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1016 packet_start(SSH_CMSG_EXEC_CMD);
1017 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1019 packet_write_wait();
1021 debug("Requesting shell.");
1022 packet_start(SSH_CMSG_EXEC_SHELL);
1024 packet_write_wait();
1027 /* Enter the interactive session. */
1028 return client_loop(have_tty, tty_flag ?
1029 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1033 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1037 id = packet_get_int();
1038 len = buffer_len(&command);
1042 if (type == SSH2_MSG_CHANNEL_FAILURE)
1043 fatal("Request for subsystem '%.*s' failed on channel %d",
1044 len, (u_char *)buffer_ptr(&command), id);
1048 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1052 i = client_global_request_id++;
1053 if (i >= options.num_remote_forwards)
1055 debug("remote forward %s for: listen %d, connect %s:%d",
1056 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1057 options.remote_forwards[i].port,
1058 options.remote_forwards[i].host,
1059 options.remote_forwards[i].host_port);
1060 if (type == SSH2_MSG_REQUEST_FAILURE)
1061 logit("Warning: remote port forwarding failed for listen port %d",
1062 options.remote_forwards[i].port);
1066 ssh_control_listener(void)
1068 struct sockaddr_un addr;
1072 if (options.control_path == NULL || options.control_master <= 0)
1075 memset(&addr, '\0', sizeof(addr));
1076 addr.sun_family = AF_UNIX;
1077 addr_len = offsetof(struct sockaddr_un, sun_path) +
1078 strlen(options.control_path) + 1;
1080 if (strlcpy(addr.sun_path, options.control_path,
1081 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1082 fatal("ControlPath too long");
1084 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1085 fatal("%s socket(): %s\n", __func__, strerror(errno));
1087 old_umask = umask(0177);
1088 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1090 if (errno == EINVAL)
1091 fatal("ControlSocket %s already exists",
1092 options.control_path);
1094 fatal("%s bind(): %s\n", __func__, strerror(errno));
1098 if (listen(control_fd, 64) == -1)
1099 fatal("%s listen(): %s\n", __func__, strerror(errno));
1101 set_nonblock(control_fd);
1104 /* request pty/x11/agent/tcpfwd/shell for channel */
1106 ssh_session2_setup(int id, void *arg)
1108 extern char **environ;
1110 int interactive = tty_flag;
1111 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
1113 /* Get reasonable local authentication information. */
1114 x11_get_proto(&proto, &data);
1115 /* Request forwarding with authentication spoofing. */
1116 debug("Requesting X11 forwarding with authentication spoofing.");
1117 x11_request_forwarding_with_spoofing(id, proto, data);
1119 /* XXX wait for reply */
1122 check_agent_present();
1123 if (options.forward_agent) {
1124 debug("Requesting authentication agent forwarding.");
1125 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1129 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1130 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1132 packet_set_interactive(interactive);
1135 /* open new channel for a session */
1137 ssh_session2_open(void)
1140 int window, packetmax, in, out, err;
1142 if (stdin_null_flag) {
1143 in = open(_PATH_DEVNULL, O_RDONLY);
1145 in = dup(STDIN_FILENO);
1147 out = dup(STDOUT_FILENO);
1148 err = dup(STDERR_FILENO);
1150 if (in < 0 || out < 0 || err < 0)
1151 fatal("dup() in/out/err failed");
1153 /* enable nonblocking unless tty */
1161 window = CHAN_SES_WINDOW_DEFAULT;
1162 packetmax = CHAN_SES_PACKET_DEFAULT;
1168 "session", SSH_CHANNEL_OPENING, in, out, err,
1169 window, packetmax, CHAN_EXTENDED_WRITE,
1170 "client-session", /*nonblock*/0);
1172 debug3("ssh_session2_open: channel_new: %d", c->self);
1174 channel_send_open(c->self);
1176 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1186 /* XXX should be pre-session */
1187 ssh_init_forwarding();
1188 ssh_control_listener();
1190 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1191 id = ssh_session2_open();
1193 /* If requested, let ssh continue in the background. */
1194 if (fork_after_authentication_flag)
1195 if (daemon(1, 1) < 0)
1196 fatal("daemon() failed: %.200s", strerror(errno));
1198 return client_loop(tty_flag, tty_flag ?
1199 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1203 load_public_identity_files(void)
1211 if (options.smartcard_device != NULL &&
1212 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1213 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1215 for (i = 0; keys[i] != NULL; i++) {
1217 memmove(&options.identity_files[1], &options.identity_files[0],
1218 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1219 memmove(&options.identity_keys[1], &options.identity_keys[0],
1220 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1221 options.num_identity_files++;
1222 options.identity_keys[0] = keys[i];
1223 options.identity_files[0] = sc_get_key_label(keys[i]);
1225 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1226 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1230 #endif /* SMARTCARD */
1231 for (; i < options.num_identity_files; i++) {
1232 filename = tilde_expand_filename(options.identity_files[i],
1234 public = key_load_public(filename, NULL);
1235 debug("identity file %s type %d", filename,
1236 public ? public->type : -1);
1237 xfree(options.identity_files[i]);
1238 options.identity_files[i] = filename;
1239 options.identity_keys[i] = public;
1244 control_client_sighandler(int signo)
1246 control_client_terminate = signo;
1250 control_client_sigrelay(int signo)
1252 if (control_server_pid > 1)
1253 kill(control_server_pid, signo);
1257 env_permitted(char *env)
1260 char name[1024], *cp;
1262 strlcpy(name, env, sizeof(name));
1263 if ((cp = strchr(name, '=')) == NULL)
1268 for (i = 0; i < options.num_send_env; i++)
1269 if (match_pattern(name, options.send_env[i]))
1276 control_client(const char *path)
1278 struct sockaddr_un addr;
1279 int i, r, sock, exitval, num_env, addr_len;
1282 extern char **environ;
1284 memset(&addr, '\0', sizeof(addr));
1285 addr.sun_family = AF_UNIX;
1286 addr_len = offsetof(struct sockaddr_un, sun_path) +
1289 if (strlcpy(addr.sun_path, path,
1290 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1291 fatal("ControlPath too long");
1293 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1294 fatal("%s socket(): %s", __func__, strerror(errno));
1296 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1)
1297 fatal("Couldn't connect to %s: %s", path, strerror(errno));
1299 if ((cp = getenv("TERM")) == NULL)
1304 /* Get PID of controlee */
1305 if (ssh_msg_recv(sock, &m) == -1)
1306 fatal("%s: msg_recv", __func__);
1307 if (buffer_get_char(&m) != 0)
1308 fatal("%s: wrong version", __func__);
1309 /* Connection allowed? */
1310 if (buffer_get_int(&m) != 1)
1311 fatal("Connection to master denied");
1312 control_server_pid = buffer_get_int(&m);
1315 buffer_put_int(&m, tty_flag);
1316 buffer_put_int(&m, subsystem_flag);
1317 buffer_put_cstring(&m, cp);
1319 buffer_append(&command, "\0", 1);
1320 buffer_put_cstring(&m, buffer_ptr(&command));
1322 if (options.num_send_env == 0 || environ == NULL) {
1323 buffer_put_int(&m, 0);
1325 /* Pass environment */
1327 for (i = 0; environ[i] != NULL; i++)
1328 if (env_permitted(environ[i]))
1329 num_env++; /* Count */
1331 buffer_put_int(&m, num_env);
1333 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1334 if (env_permitted(environ[i])) {
1336 buffer_put_cstring(&m, environ[i]);
1340 if (ssh_msg_send(sock, /* version */0, &m) == -1)
1341 fatal("%s: msg_send", __func__);
1343 mm_send_fd(sock, STDIN_FILENO);
1344 mm_send_fd(sock, STDOUT_FILENO);
1345 mm_send_fd(sock, STDERR_FILENO);
1347 /* Wait for reply, so master has a chance to gather ttymodes */
1349 if (ssh_msg_recv(sock, &m) == -1)
1350 fatal("%s: msg_recv", __func__);
1351 if (buffer_get_char(&m) != 0)
1352 fatal("%s: master returned error", __func__);
1355 signal(SIGINT, control_client_sighandler);
1356 signal(SIGTERM, control_client_sighandler);
1357 signal(SIGWINCH, control_client_sigrelay);
1362 /* Stick around until the controlee closes the client_fd */
1364 for (;!control_client_terminate;) {
1365 r = read(sock, &exitval, sizeof(exitval));
1367 debug2("Received EOF from master");
1371 debug2("Received exit status from master %d", exitval);
1372 if (r == -1 && errno != EINTR)
1373 fatal("%s: read %s", __func__, strerror(errno));
1376 if (control_client_terminate)
1377 debug2("Exiting on signal %d", control_client_terminate);
1383 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1384 fprintf(stderr, "Connection to master closed.\r\n");