1 /* $OpenBSD: ssh.c,v 1.289 2006/07/22 20:48:23 stevesk Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Ssh client program. This program can be used to log into a remote machine.
7 * The software supports strong authentication, encryption, and forwarding
8 * of X11, TCP/IP, and authentication connections.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
19 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
67 #include <openssl/evp.h>
68 #include <openssl/err.h>
83 #include "pathnames.h"
85 #include "clientloop.h"
88 #include "sshconnect.h"
95 #include "monitor_fdpass.h"
103 extern char *__progname
;
105 /* Flag indicating whether debug mode is on. This can be set on the command line. */
108 /* Flag indicating whether a tty should be allocated */
111 int force_tty_flag
= 0;
113 /* don't exec a shell */
114 int no_shell_flag
= 0;
117 * Flag indicating that nothing should be read from stdin. This can be set
118 * on the command line.
120 int stdin_null_flag
= 0;
123 * Flag indicating that ssh should fork after authentication. This is useful
124 * so that the passphrase can be entered manually, and then ssh goes to the
127 int fork_after_authentication_flag
= 0;
130 * General data structure for command line options and options configurable
131 * in configuration files. See readconf.h.
135 /* optional user configfile */
139 * Name of the host we are connecting to. This is the name given on the
140 * command line, or the HostName specified for the user-supplied name in a
141 * configuration file.
145 /* socket address the host resolves to */
146 struct sockaddr_storage hostaddr
;
148 /* Private host keys. */
149 Sensitive sensitive_data
;
151 /* Original real UID. */
152 uid_t original_real_uid
;
153 uid_t original_effective_uid
;
155 /* command to be executed */
158 /* Should we execute a command or invoke a subsystem? */
159 int subsystem_flag
= 0;
161 /* # of replies received for global requests */
162 static int client_global_request_id
= 0;
164 /* pid of proxycommand child process */
165 pid_t proxy_command_pid
= 0;
167 /* fd to control socket */
170 /* Multiplexing control command */
171 static u_int mux_command
= 0;
173 /* Only used in control client mode */
174 volatile sig_atomic_t control_client_terminate
= 0;
175 u_int control_server_pid
= 0;
177 /* Prints a help message to the user. This function never returns. */
183 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
184 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
185 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
186 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
187 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
188 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
193 static int ssh_session(void);
194 static int ssh_session2(void);
195 static void load_public_identity_files(void);
196 static void control_client(const char *path
);
199 * Main program for the ssh client.
202 main(int ac
, char **av
)
204 int i
, opt
, exit_status
;
205 char *p
, *cp
, *line
, buf
[256];
209 extern int optind
, optreset
;
214 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
217 __progname
= ssh_get_progname(av
[0]);
221 * Save the original real uid. It will be needed later (uid-swapping
222 * may clobber the real uid).
224 original_real_uid
= getuid();
225 original_effective_uid
= geteuid();
228 * Use uid-swapping to give up root privileges for the duration of
229 * option processing. We will re-instantiate the rights when we are
230 * ready to create the privileged port, and will permanently drop
231 * them when the port has been created (actually, when the connection
232 * has been made, as we may need to create the port several times).
236 #ifdef HAVE_SETRLIMIT
237 /* If we are installed setuid root be careful to not drop core. */
238 if (original_real_uid
!= original_effective_uid
) {
240 rlim
.rlim_cur
= rlim
.rlim_max
= 0;
241 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
242 fatal("setrlimit failed: %.100s", strerror(errno
));
246 pw
= getpwuid(original_real_uid
);
248 logit("You don't exist, go away!");
251 /* Take a copy of the returned structure. */
255 * Set our umask to something reasonable, as some files are created
256 * with the default umask. This will make them world-readable but
257 * writable only by the owner, which is ok for all files for which we
258 * don't set the modes explicitly.
262 /* Initialize option structure to indicate that no values have been set. */
263 initialize_options(&options
);
265 /* Parse command-line arguments. */
269 while ((opt
= getopt(ac
, av
,
270 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
273 options
.protocol
= SSH_PROTO_1
;
276 options
.protocol
= SSH_PROTO_2
;
279 options
.address_family
= AF_INET
;
282 options
.address_family
= AF_INET6
;
288 fork_after_authentication_flag
= 1;
292 options
.forward_x11
= 0;
295 options
.forward_x11
= 1;
298 options
.forward_x11
= 1;
299 options
.forward_x11_trusted
= 1;
302 options
.gateway_ports
= 1;
305 if (strcmp(optarg
, "check") == 0)
306 mux_command
= SSHMUX_COMMAND_ALIVE_CHECK
;
307 else if (strcmp(optarg
, "exit") == 0)
308 mux_command
= SSHMUX_COMMAND_TERMINATE
;
310 fatal("Invalid multiplex command.");
312 case 'P': /* deprecated */
313 options
.use_privileged_port
= 0;
316 options
.forward_agent
= 0;
319 options
.forward_agent
= 1;
322 options
.gss_deleg_creds
= 0;
325 if (stat(optarg
, &st
) < 0) {
326 fprintf(stderr
, "Warning: Identity file %s "
327 "not accessible: %s.\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 (debug_flag
== 0) {
353 options
.log_level
= SYSLOG_LEVEL_DEBUG1
;
355 if (options
.log_level
< SYSLOG_LEVEL_DEBUG3
)
361 fprintf(stderr
, "%s, %s\n",
362 SSH_RELEASE
, SSLeay_version(SSLEAY_VERSION
));
367 if (options
.tun_open
== -1)
368 options
.tun_open
= SSH_TUNMODE_DEFAULT
;
369 options
.tun_local
= a2tun(optarg
, &options
.tun_remote
);
370 if (options
.tun_local
== SSH_TUNID_ERR
) {
371 fprintf(stderr
, "Bad tun device '%s'\n", optarg
);
376 options
.log_level
= SYSLOG_LEVEL_QUIET
;
379 if (optarg
[0] == '^' && optarg
[2] == 0 &&
380 (u_char
) optarg
[1] >= 64 &&
381 (u_char
) optarg
[1] < 128)
382 options
.escape_char
= (u_char
) optarg
[1] & 31;
383 else if (strlen(optarg
) == 1)
384 options
.escape_char
= (u_char
) optarg
[0];
385 else if (strcmp(optarg
, "none") == 0)
386 options
.escape_char
= SSH_ESCAPECHAR_NONE
;
388 fprintf(stderr
, "Bad escape character '%s'.\n",
394 if (ciphers_valid(optarg
)) {
396 options
.ciphers
= xstrdup(optarg
);
397 options
.cipher
= SSH_CIPHER_INVALID
;
400 options
.cipher
= cipher_number(optarg
);
401 if (options
.cipher
== -1) {
403 "Unknown cipher type '%s'\n",
407 if (options
.cipher
== SSH_CIPHER_3DES
)
408 options
.ciphers
= "3des-cbc";
409 else if (options
.cipher
== SSH_CIPHER_BLOWFISH
)
410 options
.ciphers
= "blowfish-cbc";
412 options
.ciphers
= (char *)-1;
416 if (mac_valid(optarg
))
417 options
.macs
= xstrdup(optarg
);
419 fprintf(stderr
, "Unknown mac type '%s'\n",
425 if (options
.control_master
== SSHCTL_MASTER_YES
)
426 options
.control_master
= SSHCTL_MASTER_ASK
;
428 options
.control_master
= SSHCTL_MASTER_YES
;
431 options
.port
= a2port(optarg
);
432 if (options
.port
== 0) {
433 fprintf(stderr
, "Bad port '%s'\n", optarg
);
438 options
.user
= optarg
;
442 if (parse_forward(&fwd
, optarg
))
443 add_local_forward(&options
, &fwd
);
446 "Bad local forwarding specification '%s'\n",
453 if (parse_forward(&fwd
, optarg
)) {
454 add_remote_forward(&options
, &fwd
);
457 "Bad remote forwarding specification "
464 cp
= p
= xstrdup(optarg
);
465 memset(&fwd
, '\0', sizeof(fwd
));
466 fwd
.connect_host
= "socks";
467 if ((fwd
.listen_host
= hpdelim(&cp
)) == NULL
) {
468 fprintf(stderr
, "Bad dynamic forwarding "
469 "specification '%.100s'\n", optarg
);
473 fwd
.listen_port
= a2port(cp
);
474 fwd
.listen_host
= cleanhostname(fwd
.listen_host
);
476 fwd
.listen_port
= a2port(fwd
.listen_host
);
477 fwd
.listen_host
= NULL
;
480 if (fwd
.listen_port
== 0) {
481 fprintf(stderr
, "Bad dynamic port '%s'\n",
485 add_local_forward(&options
, &fwd
);
490 options
.compression
= 1;
501 line
= xstrdup(optarg
);
502 if (process_config_line(&options
, host
? host
: "",
503 line
, "command-line", 0, &dummy
) != 0)
511 if (options
.control_path
!= NULL
)
512 free(options
.control_path
);
513 options
.control_path
= xstrdup(optarg
);
516 options
.bind_address
= optarg
;
529 if (ac
> 0 && !host
&& **av
!= '-') {
530 if (strrchr(*av
, '@')) {
532 cp
= strrchr(p
, '@');
533 if (cp
== NULL
|| cp
== p
)
541 optind
= optreset
= 1;
547 /* Check that we got a host name. */
551 SSLeay_add_all_algorithms();
552 ERR_load_crypto_strings();
554 /* Initialize the command to execute on remote host. */
555 buffer_init(&command
);
558 * Save the command to execute on the remote host in a buffer. There
559 * is no limit on the length of the command, except by the maximum
560 * packet size. Also sets the tty flag if there is no command.
563 /* No command specified - execute shell on a tty. */
565 if (subsystem_flag
) {
567 "You must specify a subsystem to invoke.\n");
571 /* A command has been specified. Store it into the buffer. */
572 for (i
= 0; i
< ac
; i
++) {
574 buffer_append(&command
, " ", 1);
575 buffer_append(&command
, av
[i
], strlen(av
[i
]));
579 /* Cannot fork to background if no command. */
580 if (fork_after_authentication_flag
&& buffer_len(&command
) == 0 && !no_shell_flag
)
581 fatal("Cannot fork into background without a command to execute.");
583 /* Allocate a tty by default if no command specified. */
584 if (buffer_len(&command
) == 0)
590 /* Do not allocate a tty if stdin is not a tty. */
591 if ((!isatty(fileno(stdin
)) || stdin_null_flag
) && !force_tty_flag
) {
593 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
598 * Initialize "log" output. Since we are the client all output
599 * actually goes to stderr.
601 log_init(av
[0], options
.log_level
== -1 ? SYSLOG_LEVEL_INFO
: options
.log_level
,
602 SYSLOG_FACILITY_USER
, 1);
605 * Read per-user configuration file. Ignore the system wide config
606 * file if the user specifies a config file on the command line.
608 if (config
!= NULL
) {
609 if (!read_config_file(config
, host
, &options
, 0))
610 fatal("Can't open user config file %.100s: "
611 "%.100s", config
, strerror(errno
));
613 snprintf(buf
, sizeof buf
, "%.100s/%.100s", pw
->pw_dir
,
614 _PATH_SSH_USER_CONFFILE
);
615 (void)read_config_file(buf
, host
, &options
, 1);
617 /* Read systemwide configuration file after use config. */
618 (void)read_config_file(_PATH_HOST_CONFIG_FILE
, host
,
622 /* Fill configuration defaults. */
623 fill_default_options(&options
);
625 channel_set_af(options
.address_family
);
628 log_init(av
[0], options
.log_level
, SYSLOG_FACILITY_USER
, 1);
632 if (options
.user
== NULL
)
633 options
.user
= xstrdup(pw
->pw_name
);
635 if (options
.hostname
!= NULL
)
636 host
= options
.hostname
;
638 /* force lowercase for hostkey matching */
639 if (options
.host_key_alias
!= NULL
) {
640 for (p
= options
.host_key_alias
; *p
; p
++)
642 *p
= (char)tolower(*p
);
645 /* Get default port if port has not been set. */
646 if (options
.port
== 0) {
647 sp
= getservbyname(SSH_SERVICE_NAME
, "tcp");
648 options
.port
= sp
? ntohs(sp
->s_port
) : SSH_DEFAULT_PORT
;
651 if (options
.proxy_command
!= NULL
&&
652 strcmp(options
.proxy_command
, "none") == 0)
653 options
.proxy_command
= NULL
;
654 if (options
.control_path
!= NULL
&&
655 strcmp(options
.control_path
, "none") == 0)
656 options
.control_path
= NULL
;
658 if (options
.control_path
!= NULL
) {
659 char thishost
[NI_MAXHOST
];
661 if (gethostname(thishost
, sizeof(thishost
)) == -1)
662 fatal("gethostname: %s", strerror(errno
));
663 snprintf(buf
, sizeof(buf
), "%d", options
.port
);
664 cp
= tilde_expand_filename(options
.control_path
,
666 options
.control_path
= percent_expand(cp
, "p", buf
, "h", host
,
667 "r", options
.user
, "l", thishost
, (char *)NULL
);
670 if (mux_command
!= 0 && options
.control_path
== NULL
)
671 fatal("No ControlPath specified for \"-O\" command");
672 if (options
.control_path
!= NULL
)
673 control_client(options
.control_path
);
675 /* Open a connection to the remote host. */
676 if (ssh_connect(host
, &hostaddr
, options
.port
,
677 options
.address_family
, options
.connection_attempts
,
679 options
.use_privileged_port
,
681 original_effective_uid
== 0 && options
.use_privileged_port
,
683 options
.proxy_command
) != 0)
687 * If we successfully made the connection, load the host private key
688 * in case we will need it later for combined rsa-rhosts
689 * authentication. This must be done before releasing extra
690 * privileges, because the file is only readable by root.
691 * If we cannot access the private keys, load the public keys
692 * instead and try to execute the ssh-keysign helper instead.
694 sensitive_data
.nkeys
= 0;
695 sensitive_data
.keys
= NULL
;
696 sensitive_data
.external_keysign
= 0;
697 if (options
.rhosts_rsa_authentication
||
698 options
.hostbased_authentication
) {
699 sensitive_data
.nkeys
= 3;
700 sensitive_data
.keys
= xcalloc(sensitive_data
.nkeys
,
704 sensitive_data
.keys
[0] = key_load_private_type(KEY_RSA1
,
705 _PATH_HOST_KEY_FILE
, "", NULL
, NULL
);
706 sensitive_data
.keys
[1] = key_load_private_type(KEY_DSA
,
707 _PATH_HOST_DSA_KEY_FILE
, "", NULL
, NULL
);
708 sensitive_data
.keys
[2] = key_load_private_type(KEY_RSA
,
709 _PATH_HOST_RSA_KEY_FILE
, "", NULL
, NULL
);
712 if (options
.hostbased_authentication
== 1 &&
713 sensitive_data
.keys
[0] == NULL
&&
714 sensitive_data
.keys
[1] == NULL
&&
715 sensitive_data
.keys
[2] == NULL
) {
716 sensitive_data
.keys
[1] = key_load_public(
717 _PATH_HOST_DSA_KEY_FILE
, NULL
);
718 sensitive_data
.keys
[2] = key_load_public(
719 _PATH_HOST_RSA_KEY_FILE
, NULL
);
720 sensitive_data
.external_keysign
= 1;
724 * Get rid of any extra privileges that we may have. We will no
725 * longer need them. Also, extra privileges could make it very hard
726 * to read identity files and other non-world-readable files from the
727 * user's home directory if it happens to be on a NFS volume where
728 * root is mapped to nobody.
730 if (original_effective_uid
== 0) {
732 permanently_set_uid(pw
);
736 * Now that we are back to our own permissions, create ~/.ssh
737 * directory if it doesn't already exist.
739 snprintf(buf
, sizeof buf
, "%.100s%s%.100s", pw
->pw_dir
, strcmp(pw
->pw_dir
, "/") ? "/" : "", _PATH_SSH_USER_DIR
);
740 if (stat(buf
, &st
) < 0)
741 if (mkdir(buf
, 0700) < 0)
742 error("Could not create directory '%.200s'.", buf
);
744 /* load options.identity_files */
745 load_public_identity_files();
747 /* Expand ~ in known host file names. */
749 options
.system_hostfile
=
750 tilde_expand_filename(options
.system_hostfile
, original_real_uid
);
751 options
.user_hostfile
=
752 tilde_expand_filename(options
.user_hostfile
, original_real_uid
);
753 options
.system_hostfile2
=
754 tilde_expand_filename(options
.system_hostfile2
, original_real_uid
);
755 options
.user_hostfile2
=
756 tilde_expand_filename(options
.user_hostfile2
, original_real_uid
);
758 signal(SIGPIPE
, SIG_IGN
); /* ignore SIGPIPE early */
760 /* Log into the remote system. This never returns if the login fails. */
761 ssh_login(&sensitive_data
, host
, (struct sockaddr
*)&hostaddr
, pw
);
763 /* We no longer need the private host keys. Clear them now. */
764 if (sensitive_data
.nkeys
!= 0) {
765 for (i
= 0; i
< sensitive_data
.nkeys
; i
++) {
766 if (sensitive_data
.keys
[i
] != NULL
) {
767 /* Destroys contents safely */
768 debug3("clear hostkey %d", i
);
769 key_free(sensitive_data
.keys
[i
]);
770 sensitive_data
.keys
[i
] = NULL
;
773 xfree(sensitive_data
.keys
);
775 for (i
= 0; i
< options
.num_identity_files
; i
++) {
776 if (options
.identity_files
[i
]) {
777 xfree(options
.identity_files
[i
]);
778 options
.identity_files
[i
] = NULL
;
780 if (options
.identity_keys
[i
]) {
781 key_free(options
.identity_keys
[i
]);
782 options
.identity_keys
[i
] = NULL
;
786 exit_status
= compat20
? ssh_session2() : ssh_session();
789 if (options
.control_path
!= NULL
&& control_fd
!= -1)
790 unlink(options
.control_path
);
793 * Send SIGHUP to proxy command if used. We don't wait() in
794 * case it hangs and instead rely on init to reap the child
796 if (proxy_command_pid
> 1)
797 kill(proxy_command_pid
, SIGHUP
);
803 ssh_init_forwarding(void)
808 /* Initiate local TCP/IP port forwardings. */
809 for (i
= 0; i
< options
.num_local_forwards
; i
++) {
810 debug("Local connections to %.200s:%d forwarded to remote "
812 (options
.local_forwards
[i
].listen_host
== NULL
) ?
813 (options
.gateway_ports
? "*" : "LOCALHOST") :
814 options
.local_forwards
[i
].listen_host
,
815 options
.local_forwards
[i
].listen_port
,
816 options
.local_forwards
[i
].connect_host
,
817 options
.local_forwards
[i
].connect_port
);
818 success
+= channel_setup_local_fwd_listener(
819 options
.local_forwards
[i
].listen_host
,
820 options
.local_forwards
[i
].listen_port
,
821 options
.local_forwards
[i
].connect_host
,
822 options
.local_forwards
[i
].connect_port
,
823 options
.gateway_ports
);
825 if (i
> 0 && success
!= i
&& options
.exit_on_forward_failure
)
826 fatal("Could not request local forwarding.");
827 if (i
> 0 && success
== 0)
828 error("Could not request local forwarding.");
830 /* Initiate remote TCP/IP port forwardings. */
831 for (i
= 0; i
< options
.num_remote_forwards
; i
++) {
832 debug("Remote connections from %.200s:%d forwarded to "
833 "local address %.200s:%d",
834 (options
.remote_forwards
[i
].listen_host
== NULL
) ?
835 "LOCALHOST" : options
.remote_forwards
[i
].listen_host
,
836 options
.remote_forwards
[i
].listen_port
,
837 options
.remote_forwards
[i
].connect_host
,
838 options
.remote_forwards
[i
].connect_port
);
839 if (channel_request_remote_forwarding(
840 options
.remote_forwards
[i
].listen_host
,
841 options
.remote_forwards
[i
].listen_port
,
842 options
.remote_forwards
[i
].connect_host
,
843 options
.remote_forwards
[i
].connect_port
) < 0) {
844 if (options
.exit_on_forward_failure
)
845 fatal("Could not request remote forwarding.");
847 logit("Warning: Could not request remote "
854 check_agent_present(void)
856 if (options
.forward_agent
) {
857 /* Clear agent forwarding if we don't have an agent. */
858 if (!ssh_agent_present())
859 options
.forward_agent
= 0;
873 /* Enable compression if requested. */
874 if (options
.compression
) {
875 debug("Requesting compression at level %d.", options
.compression_level
);
877 if (options
.compression_level
< 1 || options
.compression_level
> 9)
878 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
880 /* Send the request. */
881 packet_start(SSH_CMSG_REQUEST_COMPRESSION
);
882 packet_put_int(options
.compression_level
);
885 type
= packet_read();
886 if (type
== SSH_SMSG_SUCCESS
)
887 packet_start_compression(options
.compression_level
);
888 else if (type
== SSH_SMSG_FAILURE
)
889 logit("Warning: Remote host refused compression.");
891 packet_disconnect("Protocol error waiting for compression response.");
893 /* Allocate a pseudo tty if appropriate. */
895 debug("Requesting pty.");
897 /* Start the packet. */
898 packet_start(SSH_CMSG_REQUEST_PTY
);
900 /* Store TERM in the packet. There is no limit on the
901 length of the string. */
905 packet_put_cstring(cp
);
907 /* Store window size in the packet. */
908 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) < 0)
909 memset(&ws
, 0, sizeof(ws
));
910 packet_put_int((u_int
)ws
.ws_row
);
911 packet_put_int((u_int
)ws
.ws_col
);
912 packet_put_int((u_int
)ws
.ws_xpixel
);
913 packet_put_int((u_int
)ws
.ws_ypixel
);
915 /* Store tty modes in the packet. */
916 tty_make_modes(fileno(stdin
), NULL
);
918 /* Send the packet, and wait for it to leave. */
922 /* Read response from the server. */
923 type
= packet_read();
924 if (type
== SSH_SMSG_SUCCESS
) {
927 } else if (type
== SSH_SMSG_FAILURE
)
928 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
930 packet_disconnect("Protocol error waiting for pty request response.");
932 /* Request X11 forwarding if enabled and DISPLAY is set. */
933 display
= getenv("DISPLAY");
934 if (options
.forward_x11
&& display
!= NULL
) {
936 /* Get reasonable local authentication information. */
937 client_x11_get_proto(display
, options
.xauth_location
,
938 options
.forward_x11_trusted
, &proto
, &data
);
939 /* Request forwarding with authentication spoofing. */
940 debug("Requesting X11 forwarding with authentication spoofing.");
941 x11_request_forwarding_with_spoofing(0, display
, proto
, data
);
943 /* Read response from the server. */
944 type
= packet_read();
945 if (type
== SSH_SMSG_SUCCESS
) {
947 } else if (type
== SSH_SMSG_FAILURE
) {
948 logit("Warning: Remote host denied X11 forwarding.");
950 packet_disconnect("Protocol error waiting for X11 forwarding");
953 /* Tell the packet module whether this is an interactive session. */
954 packet_set_interactive(interactive
);
956 /* Request authentication agent forwarding if appropriate. */
957 check_agent_present();
959 if (options
.forward_agent
) {
960 debug("Requesting authentication agent forwarding.");
961 auth_request_forwarding();
963 /* Read response from the server. */
964 type
= packet_read();
966 if (type
!= SSH_SMSG_SUCCESS
)
967 logit("Warning: Remote host denied authentication agent forwarding.");
970 /* Initiate port forwardings. */
971 ssh_init_forwarding();
973 /* If requested, let ssh continue in the background. */
974 if (fork_after_authentication_flag
)
975 if (daemon(1, 1) < 0)
976 fatal("daemon() failed: %.200s", strerror(errno
));
979 * If a command was specified on the command line, execute the
980 * command now. Otherwise request the server to start a shell.
982 if (buffer_len(&command
) > 0) {
983 int len
= buffer_len(&command
);
986 debug("Sending command: %.*s", len
, (u_char
*)buffer_ptr(&command
));
987 packet_start(SSH_CMSG_EXEC_CMD
);
988 packet_put_string(buffer_ptr(&command
), buffer_len(&command
));
992 debug("Requesting shell.");
993 packet_start(SSH_CMSG_EXEC_SHELL
);
998 /* Enter the interactive session. */
999 return client_loop(have_tty
, tty_flag
?
1000 options
.escape_char
: SSH_ESCAPECHAR_NONE
, 0);
1004 ssh_subsystem_reply(int type
, u_int32_t seq
, void *ctxt
)
1008 id
= packet_get_int();
1009 len
= buffer_len(&command
);
1013 if (type
== SSH2_MSG_CHANNEL_FAILURE
)
1014 fatal("Request for subsystem '%.*s' failed on channel %d",
1015 len
, (u_char
*)buffer_ptr(&command
), id
);
1019 client_global_request_reply_fwd(int type
, u_int32_t seq
, void *ctxt
)
1023 i
= client_global_request_id
++;
1024 if (i
>= options
.num_remote_forwards
)
1026 debug("remote forward %s for: listen %d, connect %s:%d",
1027 type
== SSH2_MSG_REQUEST_SUCCESS
? "success" : "failure",
1028 options
.remote_forwards
[i
].listen_port
,
1029 options
.remote_forwards
[i
].connect_host
,
1030 options
.remote_forwards
[i
].connect_port
);
1031 if (type
== SSH2_MSG_REQUEST_FAILURE
) {
1032 if (options
.exit_on_forward_failure
)
1033 fatal("Error: remote port forwarding failed for "
1035 options
.remote_forwards
[i
].listen_port
);
1037 logit("Warning: remote port forwarding failed for "
1039 options
.remote_forwards
[i
].listen_port
);
1044 ssh_control_listener(void)
1046 struct sockaddr_un addr
;
1050 if (options
.control_path
== NULL
||
1051 options
.control_master
== SSHCTL_MASTER_NO
)
1054 debug("setting up multiplex master socket");
1056 memset(&addr
, '\0', sizeof(addr
));
1057 addr
.sun_family
= AF_UNIX
;
1058 addr_len
= offsetof(struct sockaddr_un
, sun_path
) +
1059 strlen(options
.control_path
) + 1;
1061 if (strlcpy(addr
.sun_path
, options
.control_path
,
1062 sizeof(addr
.sun_path
)) >= sizeof(addr
.sun_path
))
1063 fatal("ControlPath too long");
1065 if ((control_fd
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
1066 fatal("%s socket(): %s", __func__
, strerror(errno
));
1068 old_umask
= umask(0177);
1069 if (bind(control_fd
, (struct sockaddr
*)&addr
, addr_len
) == -1) {
1071 if (errno
== EINVAL
|| errno
== EADDRINUSE
)
1072 fatal("ControlSocket %s already exists",
1073 options
.control_path
);
1075 fatal("%s bind(): %s", __func__
, strerror(errno
));
1079 if (listen(control_fd
, 64) == -1)
1080 fatal("%s listen(): %s", __func__
, strerror(errno
));
1082 set_nonblock(control_fd
);
1085 /* request pty/x11/agent/tcpfwd/shell for channel */
1087 ssh_session2_setup(int id
, void *arg
)
1089 extern char **environ
;
1090 const char *display
;
1091 int interactive
= tty_flag
;
1093 display
= getenv("DISPLAY");
1094 if (options
.forward_x11
&& display
!= NULL
) {
1096 /* Get reasonable local authentication information. */
1097 client_x11_get_proto(display
, options
.xauth_location
,
1098 options
.forward_x11_trusted
, &proto
, &data
);
1099 /* Request forwarding with authentication spoofing. */
1100 debug("Requesting X11 forwarding with authentication spoofing.");
1101 x11_request_forwarding_with_spoofing(id
, display
, proto
, data
);
1103 /* XXX wait for reply */
1106 check_agent_present();
1107 if (options
.forward_agent
) {
1108 debug("Requesting authentication agent forwarding.");
1109 channel_request_start(id
, "auth-agent-req@openssh.com", 0);
1113 if (options
.tun_open
!= SSH_TUNMODE_NO
) {
1117 debug("Requesting tun.");
1118 if ((fd
= tun_open(options
.tun_local
,
1119 options
.tun_open
)) >= 0) {
1120 c
= channel_new("tun", SSH_CHANNEL_OPENING
, fd
, fd
, -1,
1121 CHAN_TCP_WINDOW_DEFAULT
, CHAN_TCP_PACKET_DEFAULT
,
1124 #if defined(SSH_TUN_FILTER)
1125 if (options
.tun_open
== SSH_TUNMODE_POINTOPOINT
)
1126 channel_register_filter(c
->self
, sys_tun_infilter
,
1129 packet_start(SSH2_MSG_CHANNEL_OPEN
);
1130 packet_put_cstring("tun@openssh.com");
1131 packet_put_int(c
->self
);
1132 packet_put_int(c
->local_window_max
);
1133 packet_put_int(c
->local_maxpacket
);
1134 packet_put_int(options
.tun_open
);
1135 packet_put_int(options
.tun_remote
);
1140 client_session2_setup(id
, tty_flag
, subsystem_flag
, getenv("TERM"),
1141 NULL
, fileno(stdin
), &command
, environ
, &ssh_subsystem_reply
);
1143 packet_set_interactive(interactive
);
1146 /* open new channel for a session */
1148 ssh_session2_open(void)
1151 int window
, packetmax
, in
, out
, err
;
1153 if (stdin_null_flag
) {
1154 in
= open(_PATH_DEVNULL
, O_RDONLY
);
1156 in
= dup(STDIN_FILENO
);
1158 out
= dup(STDOUT_FILENO
);
1159 err
= dup(STDERR_FILENO
);
1161 if (in
< 0 || out
< 0 || err
< 0)
1162 fatal("dup() in/out/err failed");
1164 /* enable nonblocking unless tty */
1172 window
= CHAN_SES_WINDOW_DEFAULT
;
1173 packetmax
= CHAN_SES_PACKET_DEFAULT
;
1179 "session", SSH_CHANNEL_OPENING
, in
, out
, err
,
1180 window
, packetmax
, CHAN_EXTENDED_WRITE
,
1181 "client-session", /*nonblock*/0);
1183 debug3("ssh_session2_open: channel_new: %d", c
->self
);
1185 channel_send_open(c
->self
);
1187 channel_register_confirm(c
->self
, ssh_session2_setup
, NULL
);
1197 /* XXX should be pre-session */
1198 ssh_init_forwarding();
1199 ssh_control_listener();
1201 if (!no_shell_flag
|| (datafellows
& SSH_BUG_DUMMYCHAN
))
1202 id
= ssh_session2_open();
1204 /* Execute a local command */
1205 if (options
.local_command
!= NULL
&&
1206 options
.permit_local_command
)
1207 ssh_local_cmd(options
.local_command
);
1209 /* If requested, let ssh continue in the background. */
1210 if (fork_after_authentication_flag
)
1211 if (daemon(1, 1) < 0)
1212 fatal("daemon() failed: %.200s", strerror(errno
));
1214 return client_loop(tty_flag
, tty_flag
?
1215 options
.escape_char
: SSH_ESCAPECHAR_NONE
, id
);
1219 load_public_identity_files(void)
1221 char *filename
, *cp
, thishost
[NI_MAXHOST
];
1228 if (options
.smartcard_device
!= NULL
&&
1229 options
.num_identity_files
< SSH_MAX_IDENTITY_FILES
&&
1230 (keys
= sc_get_keys(options
.smartcard_device
, NULL
)) != NULL
) {
1232 for (i
= 0; keys
[i
] != NULL
; i
++) {
1234 memmove(&options
.identity_files
[1], &options
.identity_files
[0],
1235 sizeof(char *) * (SSH_MAX_IDENTITY_FILES
- 1));
1236 memmove(&options
.identity_keys
[1], &options
.identity_keys
[0],
1237 sizeof(Key
*) * (SSH_MAX_IDENTITY_FILES
- 1));
1238 options
.num_identity_files
++;
1239 options
.identity_keys
[0] = keys
[i
];
1240 options
.identity_files
[0] = sc_get_key_label(keys
[i
]);
1242 if (options
.num_identity_files
> SSH_MAX_IDENTITY_FILES
)
1243 options
.num_identity_files
= SSH_MAX_IDENTITY_FILES
;
1247 #endif /* SMARTCARD */
1248 if ((pw
= getpwuid(original_real_uid
)) == NULL
)
1249 fatal("load_public_identity_files: getpwuid failed");
1250 if (gethostname(thishost
, sizeof(thishost
)) == -1)
1251 fatal("load_public_identity_files: gethostname: %s",
1253 for (; i
< options
.num_identity_files
; i
++) {
1254 cp
= tilde_expand_filename(options
.identity_files
[i
],
1256 filename
= percent_expand(cp
, "d", pw
->pw_dir
,
1257 "u", pw
->pw_name
, "l", thishost
, "h", host
,
1258 "r", options
.user
, (char *)NULL
);
1260 public = key_load_public(filename
, NULL
);
1261 debug("identity file %s type %d", filename
,
1262 public ? public->type
: -1);
1263 xfree(options
.identity_files
[i
]);
1264 options
.identity_files
[i
] = filename
;
1265 options
.identity_keys
[i
] = public;
1270 control_client_sighandler(int signo
)
1272 control_client_terminate
= signo
;
1276 control_client_sigrelay(int signo
)
1278 if (control_server_pid
> 1)
1279 kill(control_server_pid
, signo
);
1283 env_permitted(char *env
)
1286 char name
[1024], *cp
;
1288 if ((cp
= strchr(env
, '=')) == NULL
|| cp
== env
)
1290 ret
= snprintf(name
, sizeof(name
), "%.*s", (int)(cp
- env
), env
);
1291 if (ret
<= 0 || (size_t)ret
>= sizeof(name
))
1292 fatal("env_permitted: name '%.100s...' too long", env
);
1294 for (i
= 0; i
< options
.num_send_env
; i
++)
1295 if (match_pattern(name
, options
.send_env
[i
]))
1302 control_client(const char *path
)
1304 struct sockaddr_un addr
;
1305 int i
, r
, fd
, sock
, exitval
, num_env
, addr_len
;
1308 extern char **environ
;
1311 if (mux_command
== 0)
1312 mux_command
= SSHMUX_COMMAND_OPEN
;
1314 switch (options
.control_master
) {
1315 case SSHCTL_MASTER_AUTO
:
1316 case SSHCTL_MASTER_AUTO_ASK
:
1317 debug("auto-mux: Trying existing master");
1319 case SSHCTL_MASTER_NO
:
1325 memset(&addr
, '\0', sizeof(addr
));
1326 addr
.sun_family
= AF_UNIX
;
1327 addr_len
= offsetof(struct sockaddr_un
, sun_path
) +
1330 if (strlcpy(addr
.sun_path
, path
,
1331 sizeof(addr
.sun_path
)) >= sizeof(addr
.sun_path
))
1332 fatal("ControlPath too long");
1334 if ((sock
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
1335 fatal("%s socket(): %s", __func__
, strerror(errno
));
1337 if (connect(sock
, (struct sockaddr
*)&addr
, addr_len
) == -1) {
1338 if (mux_command
!= SSHMUX_COMMAND_OPEN
) {
1339 fatal("Control socket connect(%.100s): %s", path
,
1342 if (errno
== ENOENT
)
1343 debug("Control socket \"%.100s\" does not exist", path
);
1345 error("Control socket connect(%.100s): %s", path
,
1352 if (stdin_null_flag
) {
1353 if ((fd
= open(_PATH_DEVNULL
, O_RDONLY
)) == -1)
1354 fatal("open(/dev/null): %s", strerror(errno
));
1355 if (dup2(fd
, STDIN_FILENO
) == -1)
1356 fatal("dup2: %s", strerror(errno
));
1357 if (fd
> STDERR_FILENO
)
1361 term
= getenv("TERM");
1365 flags
|= SSHMUX_FLAG_TTY
;
1367 flags
|= SSHMUX_FLAG_SUBSYS
;
1368 if (options
.forward_x11
)
1369 flags
|= SSHMUX_FLAG_X11_FWD
;
1370 if (options
.forward_agent
)
1371 flags
|= SSHMUX_FLAG_AGENT_FWD
;
1375 /* Send our command to server */
1376 buffer_put_int(&m
, mux_command
);
1377 buffer_put_int(&m
, flags
);
1378 if (ssh_msg_send(sock
, SSHMUX_VER
, &m
) == -1)
1379 fatal("%s: msg_send", __func__
);
1382 /* Get authorisation status and PID of controlee */
1383 if (ssh_msg_recv(sock
, &m
) == -1)
1384 fatal("%s: msg_recv", __func__
);
1385 if (buffer_get_char(&m
) != SSHMUX_VER
)
1386 fatal("%s: wrong version", __func__
);
1387 if (buffer_get_int(&m
) != 1)
1388 fatal("Connection to master denied");
1389 control_server_pid
= buffer_get_int(&m
);
1393 switch (mux_command
) {
1394 case SSHMUX_COMMAND_ALIVE_CHECK
:
1395 fprintf(stderr
, "Master running (pid=%d)\r\n",
1396 control_server_pid
);
1398 case SSHMUX_COMMAND_TERMINATE
:
1399 fprintf(stderr
, "Exit request sent.\r\n");
1401 case SSHMUX_COMMAND_OPEN
:
1402 /* continue below */
1405 fatal("silly mux_command %d", mux_command
);
1408 /* SSHMUX_COMMAND_OPEN */
1409 buffer_put_cstring(&m
, term
? term
: "");
1410 buffer_append(&command
, "\0", 1);
1411 buffer_put_cstring(&m
, buffer_ptr(&command
));
1413 if (options
.num_send_env
== 0 || environ
== NULL
) {
1414 buffer_put_int(&m
, 0);
1416 /* Pass environment */
1418 for (i
= 0; environ
[i
] != NULL
; i
++)
1419 if (env_permitted(environ
[i
]))
1420 num_env
++; /* Count */
1422 buffer_put_int(&m
, num_env
);
1424 for (i
= 0; environ
[i
] != NULL
&& num_env
>= 0; i
++)
1425 if (env_permitted(environ
[i
])) {
1427 buffer_put_cstring(&m
, environ
[i
]);
1431 if (ssh_msg_send(sock
, SSHMUX_VER
, &m
) == -1)
1432 fatal("%s: msg_send", __func__
);
1434 mm_send_fd(sock
, STDIN_FILENO
);
1435 mm_send_fd(sock
, STDOUT_FILENO
);
1436 mm_send_fd(sock
, STDERR_FILENO
);
1438 /* Wait for reply, so master has a chance to gather ttymodes */
1440 if (ssh_msg_recv(sock
, &m
) == -1)
1441 fatal("%s: msg_recv", __func__
);
1442 if (buffer_get_char(&m
) != SSHMUX_VER
)
1443 fatal("%s: wrong version", __func__
);
1446 signal(SIGHUP
, control_client_sighandler
);
1447 signal(SIGINT
, control_client_sighandler
);
1448 signal(SIGTERM
, control_client_sighandler
);
1449 signal(SIGWINCH
, control_client_sigrelay
);
1454 /* Stick around until the controlee closes the client_fd */
1456 for (;!control_client_terminate
;) {
1457 r
= read(sock
, &exitval
, sizeof(exitval
));
1459 debug2("Received EOF from master");
1463 debug2("Received exit status from master %d", exitval
);
1464 if (r
== -1 && errno
!= EINTR
)
1465 fatal("%s: read %s", __func__
, strerror(errno
));
1468 if (control_client_terminate
)
1469 debug2("Exiting on signal %d", control_client_terminate
);
1475 if (tty_flag
&& options
.log_level
!= SYSLOG_LEVEL_QUIET
)
1476 fprintf(stderr
, "Connection to master closed.\r\n");