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.
17 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
18 * in Canada (German citizen).
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions
23 * 1. Redistributions of source code must retain the above copyright
24 * notice, this list of conditions and the following disclaimer.
25 * 2. Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
29 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 RCSID("$OpenBSD: ssh.c,v 1.167 2002/03/25 17:34:27 markus Exp $");
44 #include <openssl/evp.h>
45 #include <openssl/err.h>
60 #include "pathnames.h"
61 #include "clientloop.h"
64 #include "sshconnect.h"
65 #include "tildexpand.h"
76 #ifdef HAVE___PROGNAME
77 extern char *__progname;
82 /* Flag indicating whether IPv4 or IPv6. This can be set on the command line.
83 Default value is AF_UNSPEC means both IPv4 and IPv6. */
85 int IPv4or6 = AF_INET;
87 int IPv4or6 = AF_UNSPEC;
90 /* Flag indicating whether debug mode is on. This can be set on the command line. */
93 /* Flag indicating whether a tty should be allocated */
96 int force_tty_flag = 0;
98 /* don't exec a shell */
99 int no_shell_flag = 0;
102 * Flag indicating that nothing should be read from stdin. This can be set
103 * on the command line.
105 int stdin_null_flag = 0;
108 * Flag indicating that ssh should fork after authentication. This is useful
109 * so that the pasphrase can be entered manually, and then ssh goes to the
112 int fork_after_authentication_flag = 0;
115 * General data structure for command line options and options configurable
116 * in configuration files. See readconf.h.
120 /* optional user configfile */
124 * Name of the host we are connecting to. This is the name given on the
125 * command line, or the HostName specified for the user-supplied name in a
126 * configuration file.
130 /* socket address the host resolves to */
131 struct sockaddr_storage hostaddr;
133 /* Private host keys. */
139 /* Original real UID. */
140 uid_t original_real_uid;
142 /* command to be executed */
145 /* Should we execute a command or invoke a subsystem? */
146 int subsystem_flag = 0;
148 /* Prints a help message to the user. This function never returns. */
153 fprintf(stderr, "Usage: %s [options] host [command]\n", __progname);
154 fprintf(stderr, "Options:\n");
155 fprintf(stderr, " -l user Log in using this user name.\n");
156 fprintf(stderr, " -n Redirect input from " _PATH_DEVNULL ".\n");
157 fprintf(stderr, " -F config Config file (default: ~/%s).\n",
158 _PATH_SSH_USER_CONFFILE);
159 fprintf(stderr, " -A Enable authentication agent forwarding.\n");
160 fprintf(stderr, " -a Disable authentication agent forwarding (default).\n");
162 fprintf(stderr, " -k Disable Kerberos ticket and AFS token forwarding.\n");
164 fprintf(stderr, " -X Enable X11 connection forwarding.\n");
165 fprintf(stderr, " -x Disable X11 connection forwarding (default).\n");
166 fprintf(stderr, " -i file Identity for public key authentication "
167 "(default: ~/.ssh/identity)\n");
169 fprintf(stderr, " -I reader Set smartcard reader.\n");
171 fprintf(stderr, " -t Tty; allocate a tty even if command is given.\n");
172 fprintf(stderr, " -T Do not allocate a tty.\n");
173 fprintf(stderr, " -v Verbose; display verbose debugging messages.\n");
174 fprintf(stderr, " Multiple -v increases verbosity.\n");
175 fprintf(stderr, " -V Display version number only.\n");
176 fprintf(stderr, " -P Don't allocate a privileged port.\n");
177 fprintf(stderr, " -q Quiet; don't display any warning messages.\n");
178 fprintf(stderr, " -f Fork into background after authentication.\n");
179 fprintf(stderr, " -e char Set escape character; ``none'' = disable (default: ~).\n");
181 fprintf(stderr, " -c cipher Select encryption algorithm\n");
182 fprintf(stderr, " -m macs Specify MAC algorithms for protocol version 2.\n");
183 fprintf(stderr, " -p port Connect to this port. Server must be on the same port.\n");
184 fprintf(stderr, " -L listen-port:host:port Forward local port to remote address\n");
185 fprintf(stderr, " -R listen-port:host:port Forward remote port to local address\n");
186 fprintf(stderr, " These cause %s to listen for connections on a port, and\n", __progname);
187 fprintf(stderr, " forward them to the other side by connecting to host:port.\n");
188 fprintf(stderr, " -D port Enable dynamic application-level port forwarding.\n");
189 fprintf(stderr, " -C Enable compression.\n");
190 fprintf(stderr, " -N Do not execute a shell or command.\n");
191 fprintf(stderr, " -g Allow remote hosts to connect to forwarded ports.\n");
192 fprintf(stderr, " -1 Force protocol version 1.\n");
193 fprintf(stderr, " -2 Force protocol version 2.\n");
194 fprintf(stderr, " -4 Use IPv4 only.\n");
195 fprintf(stderr, " -6 Use IPv6 only.\n");
196 fprintf(stderr, " -o 'option' Process the option as if it was read from a configuration file.\n");
197 fprintf(stderr, " -s Invoke command (mandatory) as SSH2 subsystem.\n");
198 fprintf(stderr, " -b addr Local IP address.\n");
203 * Connects to the given host using rsh (or prints an error message and exits
204 * if rsh is not available). This function never returns.
207 rsh_connect(char *host, char *user, Buffer * command)
212 log("Using rsh. WARNING: Connection will not be encrypted.");
213 /* Build argument list for rsh. */
215 args[i++] = _PATH_RSH;
216 /* host may have to come after user on some systems */
222 if (buffer_len(command) > 0) {
223 buffer_append(command, "\0", 1);
224 args[i++] = buffer_ptr(command);
228 for (i = 0; args[i]; i++) {
230 fprintf(stderr, " ");
231 fprintf(stderr, "%s", args[i]);
233 fprintf(stderr, "\n");
235 execv(_PATH_RSH, args);
240 static int ssh_session(void);
241 static int ssh_session2(void);
242 static void load_public_identity_files(void);
245 * Main program for the ssh client.
248 main(int ac, char **av)
250 int i, opt, exit_status, cerr;
251 u_short fwd_port, fwd_host_port;
252 char sfwd_port[6], sfwd_host_port[6];
253 char *p, *cp, buf[256];
257 uid_t original_effective_uid;
258 extern int optind, optreset;
261 __progname = get_progname(av[0]);
265 * Save the original real uid. It will be needed later (uid-swapping
266 * may clobber the real uid).
268 original_real_uid = getuid();
269 original_effective_uid = geteuid();
271 #ifdef HAVE_SETRLIMIT
272 /* If we are installed setuid root be careful to not drop core. */
273 if (original_real_uid != original_effective_uid) {
275 rlim.rlim_cur = rlim.rlim_max = 0;
276 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
277 fatal("setrlimit failed: %.100s", strerror(errno));
281 pw = getpwuid(original_real_uid);
283 log("You don't exist, go away!");
286 /* Take a copy of the returned structure. */
290 * Use uid-swapping to give up root privileges for the duration of
291 * option processing. We will re-instantiate the rights when we are
292 * ready to create the privileged port, and will permanently drop
293 * them when the port has been created (actually, when the connection
294 * has been made, as we may need to create the port several times).
296 temporarily_use_uid(pw);
299 * Set our umask to something reasonable, as some files are created
300 * with the default umask. This will make them world-readable but
301 * writable only by the owner, which is ok for all files for which we
302 * don't set the modes explicitly.
306 /* Initialize option structure to indicate that no values have been set. */
307 initialize_options(&options);
309 /* Parse command-line arguments. */
313 while ((opt = getopt(ac, av,
314 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:NPR:TVX")) != -1) {
317 options.protocol = SSH_PROTO_1;
320 options.protocol = SSH_PROTO_2;
332 fork_after_authentication_flag = 1;
336 options.forward_x11 = 0;
339 options.forward_x11 = 1;
342 options.gateway_ports = 1;
345 options.use_privileged_port = 0;
348 options.forward_agent = 0;
351 options.forward_agent = 1;
355 options.kerberos_tgt_passing = 0;
356 options.afs_token_passing = 0;
360 if (stat(optarg, &st) < 0) {
361 fprintf(stderr, "Warning: Identity file %s "
362 "does not exist.\n", optarg);
365 if (options.num_identity_files >=
366 SSH_MAX_IDENTITY_FILES)
367 fatal("Too many identity files specified "
368 "(max %d)", SSH_MAX_IDENTITY_FILES);
369 options.identity_files[options.num_identity_files++] =
374 options.smartcard_device = xstrdup(optarg);
376 fprintf(stderr, "no support for smartcards.\n");
385 if (0 == debug_flag) {
387 options.log_level = SYSLOG_LEVEL_DEBUG1;
388 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
392 fatal("Too high debugging level.");
396 "%s, SSH protocols %d.%d/%d.%d, OpenSSL 0x%8.8lx\n",
398 PROTOCOL_MAJOR_1, PROTOCOL_MINOR_1,
399 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2,
405 options.log_level = SYSLOG_LEVEL_QUIET;
408 if (optarg[0] == '^' && optarg[2] == 0 &&
409 (u_char) optarg[1] >= 64 &&
410 (u_char) optarg[1] < 128)
411 options.escape_char = (u_char) optarg[1] & 31;
412 else if (strlen(optarg) == 1)
413 options.escape_char = (u_char) optarg[0];
414 else if (strcmp(optarg, "none") == 0)
415 options.escape_char = SSH_ESCAPECHAR_NONE;
417 fprintf(stderr, "Bad escape character '%s'.\n",
423 if (ciphers_valid(optarg)) {
425 options.ciphers = xstrdup(optarg);
426 options.cipher = SSH_CIPHER_ILLEGAL;
429 options.cipher = cipher_number(optarg);
430 if (options.cipher == -1) {
432 "Unknown cipher type '%s'\n",
436 if (options.cipher == SSH_CIPHER_3DES)
437 options.ciphers = "3des-cbc";
438 else if (options.cipher == SSH_CIPHER_BLOWFISH)
439 options.ciphers = "blowfish-cbc";
441 options.ciphers = (char *)-1;
445 if (mac_valid(optarg))
446 options.macs = xstrdup(optarg);
448 fprintf(stderr, "Unknown mac type '%s'\n",
454 options.port = a2port(optarg);
455 if (options.port == 0) {
456 fprintf(stderr, "Bad port '%s'\n", optarg);
461 options.user = optarg;
466 if (sscanf(optarg, "%5[0-9]:%255[^:]:%5[0-9]",
467 sfwd_port, buf, sfwd_host_port) != 3 &&
468 sscanf(optarg, "%5[0-9]/%255[^/]/%5[0-9]",
469 sfwd_port, buf, sfwd_host_port) != 3) {
471 "Bad forwarding specification '%s'\n",
476 if ((fwd_port = a2port(sfwd_port)) == 0 ||
477 (fwd_host_port = a2port(sfwd_host_port)) == 0) {
479 "Bad forwarding port(s) '%s'\n", optarg);
483 add_local_forward(&options, fwd_port, buf,
486 add_remote_forward(&options, fwd_port, buf,
491 fwd_port = a2port(optarg);
493 fprintf(stderr, "Bad dynamic port '%s'\n",
497 add_local_forward(&options, fwd_port, "socks4", 0);
501 options.compression = 1;
512 if (process_config_line(&options, host ? host : "",
513 optarg, "command-line", 0, &dummy) != 0)
520 options.bind_address = optarg;
533 if (ac > 0 && !host && **av != '-') {
534 if (strchr(*av, '@')) {
537 if (cp == NULL || cp == p)
552 /* Check that we got a host name. */
556 SSLeay_add_all_algorithms();
557 ERR_load_crypto_strings();
558 channel_set_af(IPv4or6);
560 /* Initialize the command to execute on remote host. */
561 buffer_init(&command);
564 * Save the command to execute on the remote host in a buffer. There
565 * is no limit on the length of the command, except by the maximum
566 * packet size. Also sets the tty flag if there is no command.
569 /* No command specified - execute shell on a tty. */
571 if (subsystem_flag) {
573 "You must specify a subsystem to invoke.\n");
577 /* A command has been specified. Store it into the buffer. */
578 for (i = 0; i < ac; i++) {
580 buffer_append(&command, " ", 1);
581 buffer_append(&command, av[i], strlen(av[i]));
585 /* Cannot fork to background if no command. */
586 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
587 fatal("Cannot fork into background without a command to execute.");
589 /* Allocate a tty by default if no command specified. */
590 if (buffer_len(&command) == 0)
596 /* Do not allocate a tty if stdin is not a tty. */
597 if (!isatty(fileno(stdin)) && !force_tty_flag) {
599 log("Pseudo-terminal will not be allocated because stdin is not a terminal.");
604 * Initialize "log" output. Since we are the client all output
605 * actually goes to stderr.
607 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
608 SYSLOG_FACILITY_USER, 1);
611 * Read per-user configuration file. Ignore the system wide config
612 * file if the user specifies a config file on the command line.
614 if (config != NULL) {
615 if (!read_config_file(config, host, &options))
616 fatal("Can't open user config file %.100s: "
617 "%.100s", config, strerror(errno));
619 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
620 _PATH_SSH_USER_CONFFILE);
621 (void)read_config_file(buf, host, &options);
623 /* Read systemwide configuration file after use config. */
624 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host, &options);
627 /* Fill configuration defaults. */
628 fill_default_options(&options);
631 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
635 if (options.user == NULL)
636 options.user = xstrdup(pw->pw_name);
638 if (options.hostname != NULL)
639 host = options.hostname;
641 /* Disable rhosts authentication if not running as root. */
643 /* Ignore uid if running under Windows */
644 if (!options.use_privileged_port) {
646 if (original_effective_uid != 0 || !options.use_privileged_port) {
648 debug("Rhosts Authentication disabled, "
649 "originating port will not be trusted.");
650 options.rhosts_authentication = 0;
653 * If using rsh has been selected, exec it now (without trying
654 * anything else). Note that we must release privileges first.
656 if (options.use_rsh) {
658 * Restore our superuser privileges. This must be done
659 * before permanently setting the uid.
663 /* Switch to the original uid permanently. */
664 permanently_set_uid(pw);
667 rsh_connect(host, options.user, &command);
668 fatal("rsh_connect returned");
670 /* Restore our superuser privileges. */
673 /* Open a connection to the remote host. */
675 cerr = ssh_connect(host, &hostaddr, options.port, IPv4or6,
676 options.connection_attempts,
677 original_effective_uid != 0 || !options.use_privileged_port,
678 pw, options.proxy_command);
681 * If we successfully made the connection, load the host private key
682 * in case we will need it later for combined rsa-rhosts
683 * authentication. This must be done before releasing extra
684 * privileges, because the file is only readable by root.
686 sensitive_data.nkeys = 0;
687 sensitive_data.keys = NULL;
688 if (!cerr && (options.rhosts_rsa_authentication ||
689 options.hostbased_authentication)) {
690 sensitive_data.nkeys = 3;
691 sensitive_data.keys = xmalloc(sensitive_data.nkeys*sizeof(Key));
692 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
693 _PATH_HOST_KEY_FILE, "", NULL);
694 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
695 _PATH_HOST_DSA_KEY_FILE, "", NULL);
696 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
697 _PATH_HOST_RSA_KEY_FILE, "", NULL);
700 * Get rid of any extra privileges that we may have. We will no
701 * longer need them. Also, extra privileges could make it very hard
702 * to read identity files and other non-world-readable files from the
703 * user's home directory if it happens to be on a NFS volume where
704 * root is mapped to nobody.
708 * Note that some legacy systems need to postpone the following call
709 * to permanently_set_uid() until the private hostkey is destroyed
710 * with RSA_free(). Otherwise the calling user could ptrace() the
711 * process, read the private hostkey and impersonate the host.
712 * OpenBSD does not allow ptracing of setuid processes.
714 permanently_set_uid(pw);
717 * Now that we are back to our own permissions, create ~/.ssh
718 * directory if it doesn\'t already exist.
720 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
721 if (stat(buf, &st) < 0)
722 if (mkdir(buf, 0700) < 0)
723 error("Could not create directory '%.200s'.", buf);
725 /* Check if the connection failed, and try "rsh" if appropriate. */
727 if (!options.fallback_to_rsh)
729 if (options.port != 0)
730 log("Secure connection to %.100s on port %hu refused; "
731 "reverting to insecure method",
734 log("Secure connection to %.100s refused; "
735 "reverting to insecure method.", host);
737 rsh_connect(host, options.user, &command);
738 fatal("rsh_connect returned");
740 /* load options.identity_files */
741 load_public_identity_files();
743 /* Expand ~ in known host file names. */
745 options.system_hostfile =
746 tilde_expand_filename(options.system_hostfile, original_real_uid);
747 options.user_hostfile =
748 tilde_expand_filename(options.user_hostfile, original_real_uid);
749 options.system_hostfile2 =
750 tilde_expand_filename(options.system_hostfile2, original_real_uid);
751 options.user_hostfile2 =
752 tilde_expand_filename(options.user_hostfile2, original_real_uid);
754 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
756 /* Log into the remote system. This never returns if the login fails. */
757 ssh_login(sensitive_data.keys, sensitive_data.nkeys,
758 host, (struct sockaddr *)&hostaddr, pw);
760 /* We no longer need the private host keys. Clear them now. */
761 if (sensitive_data.nkeys != 0) {
762 for (i = 0; i < sensitive_data.nkeys; i++) {
763 if (sensitive_data.keys[i] != NULL) {
764 /* Destroys contents safely */
765 debug3("clear hostkey %d", i);
766 key_free(sensitive_data.keys[i]);
767 sensitive_data.keys[i] = NULL;
770 xfree(sensitive_data.keys);
772 for (i = 0; i < options.num_identity_files; i++) {
773 if (options.identity_files[i]) {
774 xfree(options.identity_files[i]);
775 options.identity_files[i] = NULL;
777 if (options.identity_keys[i]) {
778 key_free(options.identity_keys[i]);
779 options.identity_keys[i] = NULL;
783 exit_status = compat20 ? ssh_session2() : ssh_session();
789 x11_get_proto(char **_proto, char **_data)
792 static char proto[512], data[512];
799 proto[0] = data[0] = '\0';
800 if (options.xauth_location && (display = getenv("DISPLAY"))) {
801 /* Try to get Xauthority information for the display. */
802 if (strncmp(display, "localhost:", 10) == 0)
804 * Handle FamilyLocal case where $DISPLAY does
805 * not match an authorization entry. For this we
806 * just try "xauth list unix:displaynum.screennum".
807 * XXX: "localhost" match to determine FamilyLocal
810 snprintf(line, sizeof line, "%.100s list unix:%s 2>"
811 _PATH_DEVNULL, options.xauth_location, display+10);
813 snprintf(line, sizeof line, "%.100s list %.200s 2>"
814 _PATH_DEVNULL, options.xauth_location, display);
815 debug2("x11_get_proto %s", line);
816 f = popen(line, "r");
817 if (f && fgets(line, sizeof(line), f) &&
818 sscanf(line, "%*s %511s %511s", proto, data) == 2)
824 * If we didn't get authentication data, just make up some
825 * data. The forwarding code will check the validity of the
826 * response anyway, and substitute this data. The X11
827 * server, however, will ignore this fake data and use
828 * whatever authentication mechanisms it was using otherwise
829 * for the local connection.
834 strlcpy(proto, "MIT-MAGIC-COOKIE-1", sizeof proto);
835 for (i = 0; i < 16; i++) {
838 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x", rand & 0xff);
845 ssh_init_forwarding(void)
850 /* Initiate local TCP/IP port forwardings. */
851 for (i = 0; i < options.num_local_forwards; i++) {
852 debug("Connections to local port %d forwarded to remote address %.200s:%d",
853 options.local_forwards[i].port,
854 options.local_forwards[i].host,
855 options.local_forwards[i].host_port);
856 success += channel_setup_local_fwd_listener(
857 options.local_forwards[i].port,
858 options.local_forwards[i].host,
859 options.local_forwards[i].host_port,
860 options.gateway_ports);
862 if (i > 0 && success == 0)
863 error("Could not request local forwarding.");
865 /* Initiate remote TCP/IP port forwardings. */
866 for (i = 0; i < options.num_remote_forwards; i++) {
867 debug("Connections to remote port %d forwarded to local address %.200s:%d",
868 options.remote_forwards[i].port,
869 options.remote_forwards[i].host,
870 options.remote_forwards[i].host_port);
871 channel_request_remote_forwarding(
872 options.remote_forwards[i].port,
873 options.remote_forwards[i].host,
874 options.remote_forwards[i].host_port);
879 check_agent_present(void)
881 if (options.forward_agent) {
882 /* Clear agent forwarding if we don\'t have an agent. */
883 int authfd = ssh_get_authentication_socket();
885 options.forward_agent = 0;
887 ssh_close_authentication_socket(authfd);
900 /* Enable compression if requested. */
901 if (options.compression) {
902 debug("Requesting compression at level %d.", options.compression_level);
904 if (options.compression_level < 1 || options.compression_level > 9)
905 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
907 /* Send the request. */
908 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
909 packet_put_int(options.compression_level);
912 type = packet_read();
913 if (type == SSH_SMSG_SUCCESS)
914 packet_start_compression(options.compression_level);
915 else if (type == SSH_SMSG_FAILURE)
916 log("Warning: Remote host refused compression.");
918 packet_disconnect("Protocol error waiting for compression response.");
920 /* Allocate a pseudo tty if appropriate. */
922 debug("Requesting pty.");
924 /* Start the packet. */
925 packet_start(SSH_CMSG_REQUEST_PTY);
927 /* Store TERM in the packet. There is no limit on the
928 length of the string. */
932 packet_put_cstring(cp);
934 /* Store window size in the packet. */
935 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
936 memset(&ws, 0, sizeof(ws));
937 packet_put_int(ws.ws_row);
938 packet_put_int(ws.ws_col);
939 packet_put_int(ws.ws_xpixel);
940 packet_put_int(ws.ws_ypixel);
942 /* Store tty modes in the packet. */
943 tty_make_modes(fileno(stdin), NULL);
945 /* Send the packet, and wait for it to leave. */
949 /* Read response from the server. */
950 type = packet_read();
951 if (type == SSH_SMSG_SUCCESS) {
954 } else if (type == SSH_SMSG_FAILURE)
955 log("Warning: Remote host failed or refused to allocate a pseudo tty.");
957 packet_disconnect("Protocol error waiting for pty request response.");
959 /* Request X11 forwarding if enabled and DISPLAY is set. */
960 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
962 /* Get reasonable local authentication information. */
963 x11_get_proto(&proto, &data);
964 /* Request forwarding with authentication spoofing. */
965 debug("Requesting X11 forwarding with authentication spoofing.");
966 x11_request_forwarding_with_spoofing(0, proto, data);
968 /* Read response from the server. */
969 type = packet_read();
970 if (type == SSH_SMSG_SUCCESS) {
972 } else if (type == SSH_SMSG_FAILURE) {
973 log("Warning: Remote host denied X11 forwarding.");
975 packet_disconnect("Protocol error waiting for X11 forwarding");
978 /* Tell the packet module whether this is an interactive session. */
979 packet_set_interactive(interactive);
981 /* Request authentication agent forwarding if appropriate. */
982 check_agent_present();
984 if (options.forward_agent) {
985 debug("Requesting authentication agent forwarding.");
986 auth_request_forwarding();
988 /* Read response from the server. */
989 type = packet_read();
991 if (type != SSH_SMSG_SUCCESS)
992 log("Warning: Remote host denied authentication agent forwarding.");
995 /* Initiate port forwardings. */
996 ssh_init_forwarding();
998 /* If requested, let ssh continue in the background. */
999 if (fork_after_authentication_flag)
1000 if (daemon(1, 1) < 0)
1001 fatal("daemon() failed: %.200s", strerror(errno));
1004 * If a command was specified on the command line, execute the
1005 * command now. Otherwise request the server to start a shell.
1007 if (buffer_len(&command) > 0) {
1008 int len = buffer_len(&command);
1011 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1012 packet_start(SSH_CMSG_EXEC_CMD);
1013 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1015 packet_write_wait();
1017 debug("Requesting shell.");
1018 packet_start(SSH_CMSG_EXEC_SHELL);
1020 packet_write_wait();
1023 /* Enter the interactive session. */
1024 return client_loop(have_tty, tty_flag ?
1025 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1029 client_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1033 id = packet_get_int();
1034 len = buffer_len(&command);
1038 if (type == SSH2_MSG_CHANNEL_FAILURE)
1039 fatal("Request for subsystem '%.*s' failed on channel %d",
1040 len, (u_char *)buffer_ptr(&command), id);
1043 /* request pty/x11/agent/tcpfwd/shell for channel */
1045 ssh_session2_setup(int id, void *arg)
1048 int interactive = 0;
1051 debug("ssh_session2_setup: id %d", id);
1056 cp = getenv("TERM");
1059 /* Store window size in the packet. */
1060 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1061 memset(&ws, 0, sizeof(ws));
1063 channel_request_start(id, "pty-req", 0);
1064 packet_put_cstring(cp);
1065 packet_put_int(ws.ws_col);
1066 packet_put_int(ws.ws_row);
1067 packet_put_int(ws.ws_xpixel);
1068 packet_put_int(ws.ws_ypixel);
1069 tio = get_saved_tio();
1070 tty_make_modes(/*ignored*/ 0, &tio);
1073 /* XXX wait for reply */
1075 if (options.forward_x11 &&
1076 getenv("DISPLAY") != NULL) {
1078 /* Get reasonable local authentication information. */
1079 x11_get_proto(&proto, &data);
1080 /* Request forwarding with authentication spoofing. */
1081 debug("Requesting X11 forwarding with authentication spoofing.");
1082 x11_request_forwarding_with_spoofing(id, proto, data);
1084 /* XXX wait for reply */
1087 check_agent_present();
1088 if (options.forward_agent) {
1089 debug("Requesting authentication agent forwarding.");
1090 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1094 len = buffer_len(&command);
1098 if (subsystem_flag) {
1099 debug("Sending subsystem: %.*s", len, (u_char *)buffer_ptr(&command));
1100 channel_request_start(id, "subsystem", /*want reply*/ 1);
1101 /* register callback for reply */
1102 /* XXX we asume that client_loop has already been called */
1103 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &client_subsystem_reply);
1104 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &client_subsystem_reply);
1106 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1107 channel_request_start(id, "exec", 0);
1109 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1112 channel_request_start(id, "shell", 0);
1116 packet_set_interactive(interactive);
1119 /* open new channel for a session */
1121 ssh_session2_open(void)
1124 int window, packetmax, in, out, err;
1126 if (stdin_null_flag) {
1127 in = open(_PATH_DEVNULL, O_RDONLY);
1129 in = dup(STDIN_FILENO);
1131 out = dup(STDOUT_FILENO);
1132 err = dup(STDERR_FILENO);
1134 if (in < 0 || out < 0 || err < 0)
1135 fatal("dup() in/out/err failed");
1137 /* enable nonblocking unless tty */
1145 window = CHAN_SES_WINDOW_DEFAULT;
1146 packetmax = CHAN_SES_PACKET_DEFAULT;
1152 "session", SSH_CHANNEL_OPENING, in, out, err,
1153 window, packetmax, CHAN_EXTENDED_WRITE,
1154 xstrdup("client-session"), /*nonblock*/0);
1156 debug3("ssh_session2_open: channel_new: %d", c->self);
1158 channel_send_open(c->self);
1160 channel_register_confirm(c->self, ssh_session2_setup);
1170 /* XXX should be pre-session */
1171 ssh_init_forwarding();
1173 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1174 id = ssh_session2_open();
1176 /* If requested, let ssh continue in the background. */
1177 if (fork_after_authentication_flag)
1178 if (daemon(1, 1) < 0)
1179 fatal("daemon() failed: %.200s", strerror(errno));
1181 return client_loop(tty_flag, tty_flag ?
1182 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1186 load_public_identity_files(void)
1194 if (options.smartcard_device != NULL &&
1195 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1196 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1198 for (i = 0; keys[i] != NULL; i++) {
1200 if (options.num_identity_files + 1 > SSH_MAX_IDENTITY_FILES)
1201 options.num_identity_files = SSH_MAX_IDENTITY_FILES - 1;
1202 memmove(&options.identity_files[1], &options.identity_files[0],
1203 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1204 memmove(&options.identity_keys[1], &options.identity_keys[0],
1205 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1206 options.num_identity_files++;
1207 options.identity_keys[0] = keys[i];
1208 options.identity_files[0] = xstrdup("smartcard key");;
1213 #endif /* SMARTCARD */
1214 for (; i < options.num_identity_files; i++) {
1215 filename = tilde_expand_filename(options.identity_files[i],
1217 public = key_load_public(filename, NULL);
1218 debug("identity file %s type %d", filename,
1219 public ? public->type : -1);
1220 xfree(options.identity_files[i]);
1221 options.identity_files[i] = filename;
1222 options.identity_keys[i] = public;