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 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.186 2002/09/19 01:58:18 djm Exp $");
44 RCSID("$FreeBSD: src/crypto/openssh/ssh.c,v 1.4.2.7 2003/02/03 17:31:07 des Exp $");
45 RCSID("$DragonFly: src/crypto/openssh/Attic/ssh.c,v 1.2 2003/06/17 04:24:36 dillon Exp $");
47 #include <openssl/evp.h>
48 #include <openssl/err.h>
62 #include "pathnames.h"
63 #include "clientloop.h"
66 #include "sshconnect.h"
67 #include "tildexpand.h"
78 #ifdef HAVE___PROGNAME
79 extern char *__progname;
84 /* Flag indicating whether IPv4 or IPv6. This can be set on the command line.
85 Default value is AF_UNSPEC means both IPv4 and IPv6. */
87 int IPv4or6 = AF_INET;
89 int IPv4or6 = AF_UNSPEC;
92 /* Flag indicating whether debug mode is on. This can be set on the command line. */
95 /* Flag indicating whether a tty should be allocated */
98 int force_tty_flag = 0;
100 /* don't exec a shell */
101 int no_shell_flag = 0;
104 * Flag indicating that nothing should be read from stdin. This can be set
105 * on the command line.
107 int stdin_null_flag = 0;
110 * Flag indicating that ssh should fork after authentication. This is useful
111 * so that the passphrase can be entered manually, and then ssh goes to the
114 int fork_after_authentication_flag = 0;
117 * General data structure for command line options and options configurable
118 * in configuration files. See readconf.h.
122 /* optional user configfile */
126 * Name of the host we are connecting to. This is the name given on the
127 * command line, or the HostName specified for the user-supplied name in a
128 * configuration file.
132 /* socket address the host resolves to */
133 struct sockaddr_storage hostaddr;
135 /* Private host keys. */
136 Sensitive sensitive_data;
138 /* Original real UID. */
139 uid_t original_real_uid;
140 uid_t original_effective_uid;
142 /* command to be executed */
145 /* Should we execute a command or invoke a subsystem? */
146 int subsystem_flag = 0;
148 /* # of replies received for global requests */
149 static int client_global_request_id = 0;
151 /* pid of proxycommand child process */
152 pid_t proxy_command_pid = 0;
154 /* Prints a help message to the user. This function never returns. */
159 fprintf(stderr, "Usage: %s [options] host [command]\n", __progname);
160 fprintf(stderr, "Options:\n");
161 fprintf(stderr, " -l user Log in using this user name.\n");
162 fprintf(stderr, " -n Redirect input from " _PATH_DEVNULL ".\n");
163 fprintf(stderr, " -F config Config file (default: ~/%s).\n",
164 _PATH_SSH_USER_CONFFILE);
165 fprintf(stderr, " -A Enable authentication agent forwarding.\n");
166 fprintf(stderr, " -a Disable authentication agent forwarding (default).\n");
168 fprintf(stderr, " -k Disable Kerberos ticket and AFS token forwarding.\n");
170 fprintf(stderr, " -X Enable X11 connection forwarding.\n");
171 fprintf(stderr, " -x Disable X11 connection forwarding (default).\n");
172 fprintf(stderr, " -i file Identity for public key authentication "
173 "(default: ~/.ssh/identity)\n");
175 fprintf(stderr, " -I reader Set smartcard reader.\n");
177 fprintf(stderr, " -t Tty; allocate a tty even if command is given.\n");
178 fprintf(stderr, " -T Do not allocate a tty.\n");
179 fprintf(stderr, " -v Verbose; display verbose debugging messages.\n");
180 fprintf(stderr, " Multiple -v increases verbosity.\n");
181 fprintf(stderr, " -V Display version number only.\n");
182 fprintf(stderr, " -q Quiet; don't display any warning messages.\n");
183 fprintf(stderr, " -f Fork into background after authentication.\n");
184 fprintf(stderr, " -e char Set escape character; ``none'' = disable (default: ~).\n");
186 fprintf(stderr, " -c cipher Select encryption algorithm\n");
187 fprintf(stderr, " -m macs Specify MAC algorithms for protocol version 2.\n");
188 fprintf(stderr, " -p port Connect to this port. Server must be on the same port.\n");
189 fprintf(stderr, " -L listen-port:host:port Forward local port to remote address\n");
190 fprintf(stderr, " -R listen-port:host:port Forward remote port to local address\n");
191 fprintf(stderr, " These cause %s to listen for connections on a port, and\n", __progname);
192 fprintf(stderr, " forward them to the other side by connecting to host:port.\n");
193 fprintf(stderr, " -D port Enable dynamic application-level port forwarding.\n");
194 fprintf(stderr, " -C Enable compression.\n");
195 fprintf(stderr, " -N Do not execute a shell or command.\n");
196 fprintf(stderr, " -g Allow remote hosts to connect to forwarded ports.\n");
197 fprintf(stderr, " -1 Force protocol version 1.\n");
198 fprintf(stderr, " -2 Force protocol version 2.\n");
199 fprintf(stderr, " -4 Use IPv4 only.\n");
200 fprintf(stderr, " -6 Use IPv6 only.\n");
201 fprintf(stderr, " -o 'option' Process the option as if it was read from a configuration file.\n");
202 fprintf(stderr, " -s Invoke command (mandatory) as SSH2 subsystem.\n");
203 fprintf(stderr, " -b addr Local IP address.\n");
207 static int ssh_session(void);
208 static int ssh_session2(void);
209 static void load_public_identity_files(void);
212 * Main program for the ssh client.
215 main(int ac, char **av)
217 int i, opt, exit_status;
218 u_short fwd_port, fwd_host_port;
219 char sfwd_port[6], sfwd_host_port[6];
220 char *p, *cp, buf[256];
224 extern int optind, optreset;
227 __progname = get_progname(av[0]);
231 * Save the original real uid. It will be needed later (uid-swapping
232 * may clobber the real uid).
234 original_real_uid = getuid();
235 original_effective_uid = geteuid();
238 * Use uid-swapping to give up root privileges for the duration of
239 * option processing. We will re-instantiate the rights when we are
240 * ready to create the privileged port, and will permanently drop
241 * them when the port has been created (actually, when the connection
242 * has been made, as we may need to create the port several times).
246 #ifdef HAVE_SETRLIMIT
247 /* If we are installed setuid root be careful to not drop core. */
248 if (original_real_uid != original_effective_uid) {
250 rlim.rlim_cur = rlim.rlim_max = 0;
251 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
252 fatal("setrlimit failed: %.100s", strerror(errno));
256 pw = getpwuid(original_real_uid);
258 log("unknown user %d", original_real_uid);
261 /* Take a copy of the returned structure. */
265 * Set our umask to something reasonable, as some files are created
266 * with the default umask. This will make them world-readable but
267 * writable only by the owner, which is ok for all files for which we
268 * don't set the modes explicitly.
272 /* Initialize option structure to indicate that no values have been set. */
273 initialize_options(&options);
275 /* Parse command-line arguments. */
279 while ((opt = getopt(ac, av,
280 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:NPR:TVX")) != -1) {
283 options.protocol = SSH_PROTO_1;
286 options.protocol = SSH_PROTO_2;
298 fork_after_authentication_flag = 1;
302 options.forward_x11 = 0;
305 options.forward_x11 = 1;
308 options.gateway_ports = 1;
310 case 'P': /* deprecated */
311 options.use_privileged_port = 0;
314 options.forward_agent = 0;
317 options.forward_agent = 1;
321 options.kerberos_tgt_passing = 0;
322 options.afs_token_passing = 0;
326 if (stat(optarg, &st) < 0) {
327 fprintf(stderr, "Warning: Identity file %s "
328 "does not exist.\n", optarg);
331 if (options.num_identity_files >=
332 SSH_MAX_IDENTITY_FILES)
333 fatal("Too many identity files specified "
334 "(max %d)", SSH_MAX_IDENTITY_FILES);
335 options.identity_files[options.num_identity_files++] =
340 options.smartcard_device = xstrdup(optarg);
342 fprintf(stderr, "no support for smartcards.\n");
351 if (0 == debug_flag) {
353 options.log_level = SYSLOG_LEVEL_DEBUG1;
354 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
358 fatal("Too high debugging level.");
362 "%s, SSH protocols %d.%d/%d.%d, OpenSSL 0x%8.8lx\n",
364 PROTOCOL_MAJOR_1, PROTOCOL_MINOR_1,
365 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2,
371 options.log_level = SYSLOG_LEVEL_QUIET;
374 if (optarg[0] == '^' && optarg[2] == 0 &&
375 (u_char) optarg[1] >= 64 &&
376 (u_char) optarg[1] < 128)
377 options.escape_char = (u_char) optarg[1] & 31;
378 else if (strlen(optarg) == 1)
379 options.escape_char = (u_char) optarg[0];
380 else if (strcmp(optarg, "none") == 0)
381 options.escape_char = SSH_ESCAPECHAR_NONE;
383 fprintf(stderr, "Bad escape character '%s'.\n",
389 if (ciphers_valid(optarg)) {
391 options.ciphers = xstrdup(optarg);
392 options.cipher = SSH_CIPHER_ILLEGAL;
395 options.cipher = cipher_number(optarg);
396 if (options.cipher == -1) {
398 "Unknown cipher type '%s'\n",
402 if (options.cipher == SSH_CIPHER_3DES)
403 options.ciphers = "3des-cbc";
404 else if (options.cipher == SSH_CIPHER_BLOWFISH)
405 options.ciphers = "blowfish-cbc";
407 options.ciphers = (char *)-1;
411 if (mac_valid(optarg))
412 options.macs = xstrdup(optarg);
414 fprintf(stderr, "Unknown mac type '%s'\n",
420 options.port = a2port(optarg);
421 if (options.port == 0) {
422 fprintf(stderr, "Bad port '%s'\n", optarg);
427 options.user = optarg;
432 if (sscanf(optarg, "%5[0-9]:%255[^:]:%5[0-9]",
433 sfwd_port, buf, sfwd_host_port) != 3 &&
434 sscanf(optarg, "%5[0-9]/%255[^/]/%5[0-9]",
435 sfwd_port, buf, sfwd_host_port) != 3) {
437 "Bad forwarding specification '%s'\n",
442 if ((fwd_port = a2port(sfwd_port)) == 0 ||
443 (fwd_host_port = a2port(sfwd_host_port)) == 0) {
445 "Bad forwarding port(s) '%s'\n", optarg);
449 add_local_forward(&options, fwd_port, buf,
452 add_remote_forward(&options, fwd_port, buf,
457 fwd_port = a2port(optarg);
459 fprintf(stderr, "Bad dynamic port '%s'\n",
463 add_local_forward(&options, fwd_port, "socks4", 0);
467 options.compression = 1;
478 if (process_config_line(&options, host ? host : "",
479 optarg, "command-line", 0, &dummy) != 0)
486 options.bind_address = optarg;
499 if (ac > 0 && !host && **av != '-') {
500 if (strchr(*av, '@')) {
503 if (cp == NULL || cp == p)
518 /* Check that we got a host name. */
522 SSLeay_add_all_algorithms();
523 ERR_load_crypto_strings();
524 channel_set_af(IPv4or6);
526 /* Initialize the command to execute on remote host. */
527 buffer_init(&command);
530 * Save the command to execute on the remote host in a buffer. There
531 * is no limit on the length of the command, except by the maximum
532 * packet size. Also sets the tty flag if there is no command.
535 /* No command specified - execute shell on a tty. */
537 if (subsystem_flag) {
539 "You must specify a subsystem to invoke.\n");
543 /* A command has been specified. Store it into the buffer. */
544 for (i = 0; i < ac; i++) {
546 buffer_append(&command, " ", 1);
547 buffer_append(&command, av[i], strlen(av[i]));
551 /* Cannot fork to background if no command. */
552 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
553 fatal("Cannot fork into background without a command to execute.");
555 /* Allocate a tty by default if no command specified. */
556 if (buffer_len(&command) == 0)
562 /* Do not allocate a tty if stdin is not a tty. */
563 if (!isatty(fileno(stdin)) && !force_tty_flag) {
565 log("Pseudo-terminal will not be allocated because stdin is not a terminal.");
570 * Initialize "log" output. Since we are the client all output
571 * actually goes to stderr.
573 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
574 SYSLOG_FACILITY_USER, 1);
577 * Read per-user configuration file. Ignore the system wide config
578 * file if the user specifies a config file on the command line.
580 if (config != NULL) {
581 if (!read_config_file(config, host, &options))
582 fatal("Can't open user config file %.100s: "
583 "%.100s", config, strerror(errno));
585 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
586 _PATH_SSH_USER_CONFFILE);
587 (void)read_config_file(buf, host, &options);
589 /* Read systemwide configuration file after use config. */
590 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host, &options);
593 /* Fill configuration defaults. */
594 fill_default_options(&options);
597 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
601 if (options.user == NULL)
602 options.user = xstrdup(pw->pw_name);
604 if (options.hostname != NULL)
605 host = options.hostname;
607 /* Find canonic host name. */
608 if (strchr(host, '.') == 0) {
609 struct addrinfo hints;
610 struct addrinfo *ai = NULL;
612 memset(&hints, 0, sizeof(hints));
613 hints.ai_family = IPv4or6;
614 hints.ai_flags = AI_CANONNAME;
615 hints.ai_socktype = SOCK_STREAM;
616 errgai = getaddrinfo(host, NULL, &hints, &ai);
618 if (ai->ai_canonname != NULL)
619 host = xstrdup(ai->ai_canonname);
624 /* Disable rhosts authentication if not running as root. */
626 /* Ignore uid if running under Windows */
627 if (!options.use_privileged_port) {
629 if (original_effective_uid != 0 || !options.use_privileged_port) {
631 debug("Rhosts Authentication disabled, "
632 "originating port will not be trusted.");
633 options.rhosts_authentication = 0;
635 /* Open a connection to the remote host. */
637 if (ssh_connect(host, &hostaddr, options.port, IPv4or6,
638 options.connection_attempts,
640 options.use_privileged_port,
642 original_effective_uid == 0 && options.use_privileged_port,
644 options.proxy_command) != 0)
648 * If we successfully made the connection, load the host private key
649 * in case we will need it later for combined rsa-rhosts
650 * authentication. This must be done before releasing extra
651 * privileges, because the file is only readable by root.
652 * If we cannot access the private keys, load the public keys
653 * instead and try to execute the ssh-keysign helper instead.
655 sensitive_data.nkeys = 0;
656 sensitive_data.keys = NULL;
657 sensitive_data.external_keysign = 0;
658 if (options.rhosts_rsa_authentication ||
659 options.hostbased_authentication) {
660 sensitive_data.nkeys = 3;
661 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
665 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
666 _PATH_HOST_KEY_FILE, "", NULL);
667 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
668 _PATH_HOST_DSA_KEY_FILE, "", NULL);
669 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
670 _PATH_HOST_RSA_KEY_FILE, "", NULL);
673 if (options.hostbased_authentication == 1 &&
674 sensitive_data.keys[0] == NULL &&
675 sensitive_data.keys[1] == NULL &&
676 sensitive_data.keys[2] == NULL) {
677 sensitive_data.keys[1] = key_load_public(
678 _PATH_HOST_DSA_KEY_FILE, NULL);
679 sensitive_data.keys[2] = key_load_public(
680 _PATH_HOST_RSA_KEY_FILE, NULL);
681 sensitive_data.external_keysign = 1;
685 * Get rid of any extra privileges that we may have. We will no
686 * longer need them. Also, extra privileges could make it very hard
687 * to read identity files and other non-world-readable files from the
688 * user's home directory if it happens to be on a NFS volume where
689 * root is mapped to nobody.
691 seteuid(original_real_uid);
692 setuid(original_real_uid);
695 * Now that we are back to our own permissions, create ~/.ssh
696 * directory if it doesn\'t already exist.
698 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
699 if (stat(buf, &st) < 0)
700 if (mkdir(buf, 0700) < 0)
701 error("Could not create directory '%.200s'.", buf);
703 /* load options.identity_files */
704 load_public_identity_files();
706 /* Expand ~ in known host file names. */
708 options.system_hostfile =
709 tilde_expand_filename(options.system_hostfile, original_real_uid);
710 options.user_hostfile =
711 tilde_expand_filename(options.user_hostfile, original_real_uid);
712 options.system_hostfile2 =
713 tilde_expand_filename(options.system_hostfile2, original_real_uid);
714 options.user_hostfile2 =
715 tilde_expand_filename(options.user_hostfile2, original_real_uid);
717 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
719 /* Log into the remote system. This never returns if the login fails. */
720 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
722 /* We no longer need the private host keys. Clear them now. */
723 if (sensitive_data.nkeys != 0) {
724 for (i = 0; i < sensitive_data.nkeys; i++) {
725 if (sensitive_data.keys[i] != NULL) {
726 /* Destroys contents safely */
727 debug3("clear hostkey %d", i);
728 key_free(sensitive_data.keys[i]);
729 sensitive_data.keys[i] = NULL;
732 xfree(sensitive_data.keys);
734 for (i = 0; i < options.num_identity_files; i++) {
735 if (options.identity_files[i]) {
736 xfree(options.identity_files[i]);
737 options.identity_files[i] = NULL;
739 if (options.identity_keys[i]) {
740 key_free(options.identity_keys[i]);
741 options.identity_keys[i] = NULL;
745 exit_status = compat20 ? ssh_session2() : ssh_session();
749 * Send SIGHUP to proxy command if used. We don't wait() in
750 * case it hangs and instead rely on init to reap the child
752 if (proxy_command_pid > 1)
753 kill(proxy_command_pid, SIGHUP);
759 x11_get_proto(char **_proto, char **_data)
762 static char proto[512], data[512];
770 proto[0] = data[0] = '\0';
771 if (!options.xauth_location ||
772 (stat(options.xauth_location, &st) == -1)) {
773 debug("No xauth program.");
775 if ((display = getenv("DISPLAY")) == NULL) {
776 debug("x11_get_proto: DISPLAY not set");
779 /* Try to get Xauthority information for the display. */
780 if (strncmp(display, "localhost:", 10) == 0)
782 * Handle FamilyLocal case where $DISPLAY does
783 * not match an authorization entry. For this we
784 * just try "xauth list unix:displaynum.screennum".
785 * XXX: "localhost" match to determine FamilyLocal
788 snprintf(line, sizeof line, "%s list unix:%s 2>"
789 _PATH_DEVNULL, options.xauth_location, display+10);
791 snprintf(line, sizeof line, "%s list %.200s 2>"
792 _PATH_DEVNULL, options.xauth_location, display);
793 debug2("x11_get_proto: %s", line);
794 f = popen(line, "r");
795 if (f && fgets(line, sizeof(line), f) &&
796 sscanf(line, "%*s %511s %511s", proto, data) == 2)
802 * If we didn't get authentication data, just make up some
803 * data. The forwarding code will check the validity of the
804 * response anyway, and substitute this data. The X11
805 * server, however, will ignore this fake data and use
806 * whatever authentication mechanisms it was using otherwise
807 * for the local connection.
812 log("Warning: No xauth data; using fake authentication data for X11 forwarding.");
813 strlcpy(proto, "MIT-MAGIC-COOKIE-1", sizeof proto);
814 for (i = 0; i < 16; i++) {
817 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x", rand & 0xff);
824 ssh_init_forwarding(void)
829 /* Initiate local TCP/IP port forwardings. */
830 for (i = 0; i < options.num_local_forwards; i++) {
831 debug("Connections to local port %d forwarded to remote address %.200s:%d",
832 options.local_forwards[i].port,
833 options.local_forwards[i].host,
834 options.local_forwards[i].host_port);
835 success += channel_setup_local_fwd_listener(
836 options.local_forwards[i].port,
837 options.local_forwards[i].host,
838 options.local_forwards[i].host_port,
839 options.gateway_ports);
841 if (i > 0 && success == 0)
842 error("Could not request local forwarding.");
844 /* Initiate remote TCP/IP port forwardings. */
845 for (i = 0; i < options.num_remote_forwards; i++) {
846 debug("Connections to remote port %d forwarded to local address %.200s:%d",
847 options.remote_forwards[i].port,
848 options.remote_forwards[i].host,
849 options.remote_forwards[i].host_port);
850 channel_request_remote_forwarding(
851 options.remote_forwards[i].port,
852 options.remote_forwards[i].host,
853 options.remote_forwards[i].host_port);
858 check_agent_present(void)
860 if (options.forward_agent) {
861 /* Clear agent forwarding if we don\'t have an agent. */
862 if (!ssh_agent_present())
863 options.forward_agent = 0;
876 /* Enable compression if requested. */
877 if (options.compression) {
878 debug("Requesting compression at level %d.", options.compression_level);
880 if (options.compression_level < 1 || options.compression_level > 9)
881 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
883 /* Send the request. */
884 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
885 packet_put_int(options.compression_level);
888 type = packet_read();
889 if (type == SSH_SMSG_SUCCESS)
890 packet_start_compression(options.compression_level);
891 else if (type == SSH_SMSG_FAILURE)
892 log("Warning: Remote host refused compression.");
894 packet_disconnect("Protocol error waiting for compression response.");
896 /* Allocate a pseudo tty if appropriate. */
898 debug("Requesting pty.");
900 /* Start the packet. */
901 packet_start(SSH_CMSG_REQUEST_PTY);
903 /* Store TERM in the packet. There is no limit on the
904 length of the string. */
908 packet_put_cstring(cp);
910 /* Store window size in the packet. */
911 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
912 memset(&ws, 0, sizeof(ws));
913 packet_put_int(ws.ws_row);
914 packet_put_int(ws.ws_col);
915 packet_put_int(ws.ws_xpixel);
916 packet_put_int(ws.ws_ypixel);
918 /* Store tty modes in the packet. */
919 tty_make_modes(fileno(stdin), NULL);
921 /* Send the packet, and wait for it to leave. */
925 /* Read response from the server. */
926 type = packet_read();
927 if (type == SSH_SMSG_SUCCESS) {
930 } else if (type == SSH_SMSG_FAILURE)
931 log("Warning: Remote host failed or refused to allocate a pseudo tty.");
933 packet_disconnect("Protocol error waiting for pty request response.");
935 /* Request X11 forwarding if enabled and DISPLAY is set. */
936 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
938 /* Get reasonable local authentication information. */
939 x11_get_proto(&proto, &data);
940 /* Request forwarding with authentication spoofing. */
941 debug("Requesting X11 forwarding with authentication spoofing.");
942 x11_request_forwarding_with_spoofing(0, proto, data);
944 /* Read response from the server. */
945 type = packet_read();
946 if (type == SSH_SMSG_SUCCESS) {
948 } else if (type == SSH_SMSG_FAILURE) {
949 log("Warning: Remote host denied X11 forwarding.");
951 packet_disconnect("Protocol error waiting for X11 forwarding");
954 /* Tell the packet module whether this is an interactive session. */
955 packet_set_interactive(interactive);
957 /* Request authentication agent forwarding if appropriate. */
958 check_agent_present();
960 if (options.forward_agent) {
961 debug("Requesting authentication agent forwarding.");
962 auth_request_forwarding();
964 /* Read response from the server. */
965 type = packet_read();
967 if (type != SSH_SMSG_SUCCESS)
968 log("Warning: Remote host denied authentication agent forwarding.");
971 /* Initiate port forwardings. */
972 ssh_init_forwarding();
974 /* If requested, let ssh continue in the background. */
975 if (fork_after_authentication_flag)
976 if (daemon(1, 1) < 0)
977 fatal("daemon() failed: %.200s", strerror(errno));
980 * If a command was specified on the command line, execute the
981 * command now. Otherwise request the server to start a shell.
983 if (buffer_len(&command) > 0) {
984 int len = buffer_len(&command);
987 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
988 packet_start(SSH_CMSG_EXEC_CMD);
989 packet_put_string(buffer_ptr(&command), buffer_len(&command));
993 debug("Requesting shell.");
994 packet_start(SSH_CMSG_EXEC_SHELL);
999 /* Enter the interactive session. */
1000 return client_loop(have_tty, tty_flag ?
1001 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1005 client_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1009 id = packet_get_int();
1010 len = buffer_len(&command);
1014 if (type == SSH2_MSG_CHANNEL_FAILURE)
1015 fatal("Request for subsystem '%.*s' failed on channel %d",
1016 len, (u_char *)buffer_ptr(&command), id);
1020 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
1024 i = client_global_request_id++;
1025 if (i >= options.num_remote_forwards) {
1026 debug("client_global_request_reply: too many replies %d > %d",
1027 i, options.num_remote_forwards);
1030 debug("remote forward %s for: listen %d, connect %s:%d",
1031 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1032 options.remote_forwards[i].port,
1033 options.remote_forwards[i].host,
1034 options.remote_forwards[i].host_port);
1035 if (type == SSH2_MSG_REQUEST_FAILURE)
1036 log("Warning: remote port forwarding failed for listen port %d",
1037 options.remote_forwards[i].port);
1040 /* request pty/x11/agent/tcpfwd/shell for channel */
1042 ssh_session2_setup(int id, void *arg)
1045 int interactive = 0;
1048 debug("ssh_session2_setup: id %d", id);
1053 cp = getenv("TERM");
1056 /* Store window size in the packet. */
1057 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1058 memset(&ws, 0, sizeof(ws));
1060 channel_request_start(id, "pty-req", 0);
1061 packet_put_cstring(cp);
1062 packet_put_int(ws.ws_col);
1063 packet_put_int(ws.ws_row);
1064 packet_put_int(ws.ws_xpixel);
1065 packet_put_int(ws.ws_ypixel);
1066 tio = get_saved_tio();
1067 tty_make_modes(/*ignored*/ 0, &tio);
1070 /* XXX wait for reply */
1072 if (options.forward_x11 &&
1073 getenv("DISPLAY") != NULL) {
1075 /* Get reasonable local authentication information. */
1076 x11_get_proto(&proto, &data);
1077 /* Request forwarding with authentication spoofing. */
1078 debug("Requesting X11 forwarding with authentication spoofing.");
1079 x11_request_forwarding_with_spoofing(id, proto, data);
1081 /* XXX wait for reply */
1084 check_agent_present();
1085 if (options.forward_agent) {
1086 debug("Requesting authentication agent forwarding.");
1087 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1091 len = buffer_len(&command);
1095 if (subsystem_flag) {
1096 debug("Sending subsystem: %.*s", len, (u_char *)buffer_ptr(&command));
1097 channel_request_start(id, "subsystem", /*want reply*/ 1);
1098 /* register callback for reply */
1099 /* XXX we assume that client_loop has already been called */
1100 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &client_subsystem_reply);
1101 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &client_subsystem_reply);
1103 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1104 channel_request_start(id, "exec", 0);
1106 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1109 channel_request_start(id, "shell", 0);
1113 packet_set_interactive(interactive);
1116 /* open new channel for a session */
1118 ssh_session2_open(void)
1121 int window, packetmax, in, out, err;
1123 if (stdin_null_flag) {
1124 in = open(_PATH_DEVNULL, O_RDONLY);
1126 in = dup(STDIN_FILENO);
1128 out = dup(STDOUT_FILENO);
1129 err = dup(STDERR_FILENO);
1131 if (in < 0 || out < 0 || err < 0)
1132 fatal("dup() in/out/err failed");
1134 /* enable nonblocking unless tty */
1142 window = CHAN_SES_WINDOW_DEFAULT;
1143 packetmax = CHAN_SES_PACKET_DEFAULT;
1149 "session", SSH_CHANNEL_OPENING, in, out, err,
1150 window, packetmax, CHAN_EXTENDED_WRITE,
1151 xstrdup("client-session"), /*nonblock*/0);
1153 debug3("ssh_session2_open: channel_new: %d", c->self);
1155 channel_send_open(c->self);
1157 channel_register_confirm(c->self, ssh_session2_setup);
1167 /* XXX should be pre-session */
1168 ssh_init_forwarding();
1170 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1171 id = ssh_session2_open();
1173 /* If requested, let ssh continue in the background. */
1174 if (fork_after_authentication_flag)
1175 if (daemon(1, 1) < 0)
1176 fatal("daemon() failed: %.200s", strerror(errno));
1178 return client_loop(tty_flag, tty_flag ?
1179 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1183 load_public_identity_files(void)
1191 if (options.smartcard_device != NULL &&
1192 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1193 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1195 for (i = 0; keys[i] != NULL; i++) {
1197 memmove(&options.identity_files[1], &options.identity_files[0],
1198 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1199 memmove(&options.identity_keys[1], &options.identity_keys[0],
1200 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1201 options.num_identity_files++;
1202 options.identity_keys[0] = keys[i];
1203 options.identity_files[0] = xstrdup("smartcard key");;
1205 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1206 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1210 #endif /* SMARTCARD */
1211 for (; i < options.num_identity_files; i++) {
1212 filename = tilde_expand_filename(options.identity_files[i],
1214 public = key_load_public(filename, NULL);
1215 debug("identity file %s type %d", filename,
1216 public ? public->type : -1);
1217 xfree(options.identity_files[i]);
1218 options.identity_files[i] = filename;
1219 options.identity_keys[i] = public;