1 /* $OpenBSD: ssh.c,v 1.309 2008/01/19 20:51:26 djm 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>
70 #include <netinet/in.h>
71 #include <arpa/inet.h>
73 #include <openssl/evp.h>
74 #include <openssl/err.h>
75 #include "openbsd-compat/openssl-compat.h"
89 #include "pathnames.h"
91 #include "clientloop.h"
94 #include "sshconnect.h"
101 #include "monitor_fdpass.h"
109 extern char *__progname
;
111 /* Flag indicating whether debug mode is on. This can be set on the command line. */
114 /* Flag indicating whether a tty should be allocated */
117 int force_tty_flag
= 0;
119 /* don't exec a shell */
120 int no_shell_flag
= 0;
123 * Flag indicating that nothing should be read from stdin. This can be set
124 * on the command line.
126 int stdin_null_flag
= 0;
129 * Flag indicating that ssh should fork after authentication. This is useful
130 * so that the passphrase can be entered manually, and then ssh goes to the
133 int fork_after_authentication_flag
= 0;
136 * General data structure for command line options and options configurable
137 * in configuration files. See readconf.h.
141 /* optional user configfile */
145 * Name of the host we are connecting to. This is the name given on the
146 * command line, or the HostName specified for the user-supplied name in a
147 * configuration file.
151 /* socket address the host resolves to */
152 struct sockaddr_storage hostaddr
;
154 /* Private host keys. */
155 Sensitive sensitive_data
;
157 /* Original real UID. */
158 uid_t original_real_uid
;
159 uid_t original_effective_uid
;
161 /* command to be executed */
164 /* Should we execute a command or invoke a subsystem? */
165 int subsystem_flag
= 0;
167 /* # of replies received for global requests */
168 static int client_global_request_id
= 0;
170 /* pid of proxycommand child process */
171 pid_t proxy_command_pid
= 0;
173 /* fd to control socket */
176 /* Multiplexing control command */
177 static u_int mux_command
= 0;
179 /* Only used in control client mode */
180 volatile sig_atomic_t control_client_terminate
= 0;
181 u_int control_server_pid
= 0;
183 /* Prints a help message to the user. This function never returns. */
189 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
190 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
191 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
192 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
193 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
194 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
199 static int ssh_session(void);
200 static int ssh_session2(void);
201 static void load_public_identity_files(void);
202 static void control_client(const char *path
);
205 * Main program for the ssh client.
208 main(int ac
, char **av
)
210 int i
, opt
, exit_status
;
211 char *p
, *cp
, *line
, buf
[256];
214 int dummy
, timeout_ms
;
215 extern int optind
, optreset
;
220 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
223 __progname
= ssh_get_progname(av
[0]);
227 * Save the original real uid. It will be needed later (uid-swapping
228 * may clobber the real uid).
230 original_real_uid
= getuid();
231 original_effective_uid
= geteuid();
234 * Use uid-swapping to give up root privileges for the duration of
235 * option processing. We will re-instantiate the rights when we are
236 * ready to create the privileged port, and will permanently drop
237 * them when the port has been created (actually, when the connection
238 * has been made, as we may need to create the port several times).
242 #ifdef HAVE_SETRLIMIT
243 /* If we are installed setuid root be careful to not drop core. */
244 if (original_real_uid
!= original_effective_uid
) {
246 rlim
.rlim_cur
= rlim
.rlim_max
= 0;
247 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
248 fatal("setrlimit failed: %.100s", strerror(errno
));
252 pw
= getpwuid(original_real_uid
);
254 logit("You don't exist, go away!");
257 /* Take a copy of the returned structure. */
261 * Set our umask to something reasonable, as some files are created
262 * with the default umask. This will make them world-readable but
263 * writable only by the owner, which is ok for all files for which we
264 * don't set the modes explicitly.
268 /* Initialize option structure to indicate that no values have been set. */
269 initialize_options(&options
);
271 /* Parse command-line arguments. */
275 while ((opt
= getopt(ac
, av
,
276 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:KL:MNO:PR:S:TVw:XY")) != -1) {
279 options
.protocol
= SSH_PROTO_1
;
282 options
.protocol
= SSH_PROTO_2
;
285 options
.address_family
= AF_INET
;
288 options
.address_family
= AF_INET6
;
294 fork_after_authentication_flag
= 1;
298 options
.forward_x11
= 0;
301 options
.forward_x11
= 1;
304 options
.forward_x11
= 1;
305 options
.forward_x11_trusted
= 1;
308 options
.gateway_ports
= 1;
311 if (strcmp(optarg
, "check") == 0)
312 mux_command
= SSHMUX_COMMAND_ALIVE_CHECK
;
313 else if (strcmp(optarg
, "exit") == 0)
314 mux_command
= SSHMUX_COMMAND_TERMINATE
;
316 fatal("Invalid multiplex command.");
318 case 'P': /* deprecated */
319 options
.use_privileged_port
= 0;
322 options
.forward_agent
= 0;
325 options
.forward_agent
= 1;
328 options
.gss_deleg_creds
= 0;
331 options
.gss_authentication
= 1;
332 options
.gss_deleg_creds
= 1;
335 if (stat(optarg
, &st
) < 0) {
336 fprintf(stderr
, "Warning: Identity file %s "
337 "not accessible: %s.\n", optarg
,
341 if (options
.num_identity_files
>=
342 SSH_MAX_IDENTITY_FILES
)
343 fatal("Too many identity files specified "
344 "(max %d)", SSH_MAX_IDENTITY_FILES
);
345 options
.identity_files
[options
.num_identity_files
++] =
350 options
.smartcard_device
= xstrdup(optarg
);
352 fprintf(stderr
, "no support for smartcards.\n");
361 if (debug_flag
== 0) {
363 options
.log_level
= SYSLOG_LEVEL_DEBUG1
;
365 if (options
.log_level
< SYSLOG_LEVEL_DEBUG3
)
371 fprintf(stderr
, "%s, %s\n",
372 SSH_RELEASE
, SSLeay_version(SSLEAY_VERSION
));
377 if (options
.tun_open
== -1)
378 options
.tun_open
= SSH_TUNMODE_DEFAULT
;
379 options
.tun_local
= a2tun(optarg
, &options
.tun_remote
);
380 if (options
.tun_local
== SSH_TUNID_ERR
) {
381 fprintf(stderr
, "Bad tun device '%s'\n", optarg
);
386 options
.log_level
= SYSLOG_LEVEL_QUIET
;
389 if (optarg
[0] == '^' && optarg
[2] == 0 &&
390 (u_char
) optarg
[1] >= 64 &&
391 (u_char
) optarg
[1] < 128)
392 options
.escape_char
= (u_char
) optarg
[1] & 31;
393 else if (strlen(optarg
) == 1)
394 options
.escape_char
= (u_char
) optarg
[0];
395 else if (strcmp(optarg
, "none") == 0)
396 options
.escape_char
= SSH_ESCAPECHAR_NONE
;
398 fprintf(stderr
, "Bad escape character '%s'.\n",
404 if (ciphers_valid(optarg
)) {
406 options
.ciphers
= xstrdup(optarg
);
407 options
.cipher
= SSH_CIPHER_INVALID
;
410 options
.cipher
= cipher_number(optarg
);
411 if (options
.cipher
== -1) {
413 "Unknown cipher type '%s'\n",
417 if (options
.cipher
== SSH_CIPHER_3DES
)
418 options
.ciphers
= "3des-cbc";
419 else if (options
.cipher
== SSH_CIPHER_BLOWFISH
)
420 options
.ciphers
= "blowfish-cbc";
422 options
.ciphers
= (char *)-1;
426 if (mac_valid(optarg
))
427 options
.macs
= xstrdup(optarg
);
429 fprintf(stderr
, "Unknown mac type '%s'\n",
435 if (options
.control_master
== SSHCTL_MASTER_YES
)
436 options
.control_master
= SSHCTL_MASTER_ASK
;
438 options
.control_master
= SSHCTL_MASTER_YES
;
441 options
.port
= a2port(optarg
);
442 if (options
.port
== 0) {
443 fprintf(stderr
, "Bad port '%s'\n", optarg
);
448 options
.user
= optarg
;
452 if (parse_forward(&fwd
, optarg
))
453 add_local_forward(&options
, &fwd
);
456 "Bad local forwarding specification '%s'\n",
463 if (parse_forward(&fwd
, optarg
)) {
464 add_remote_forward(&options
, &fwd
);
467 "Bad remote forwarding specification "
474 cp
= p
= xstrdup(optarg
);
475 memset(&fwd
, '\0', sizeof(fwd
));
476 fwd
.connect_host
= "socks";
477 if ((fwd
.listen_host
= hpdelim(&cp
)) == NULL
) {
478 fprintf(stderr
, "Bad dynamic forwarding "
479 "specification '%.100s'\n", optarg
);
483 fwd
.listen_port
= a2port(cp
);
484 fwd
.listen_host
= cleanhostname(fwd
.listen_host
);
486 fwd
.listen_port
= a2port(fwd
.listen_host
);
487 fwd
.listen_host
= NULL
;
490 if (fwd
.listen_port
== 0) {
491 fprintf(stderr
, "Bad dynamic port '%s'\n",
495 add_local_forward(&options
, &fwd
);
500 options
.compression
= 1;
511 line
= xstrdup(optarg
);
512 if (process_config_line(&options
, host
? host
: "",
513 line
, "command-line", 0, &dummy
) != 0)
521 if (options
.control_path
!= NULL
)
522 free(options
.control_path
);
523 options
.control_path
= xstrdup(optarg
);
526 options
.bind_address
= optarg
;
539 if (ac
> 0 && !host
&& **av
!= '-') {
540 if (strrchr(*av
, '@')) {
542 cp
= strrchr(p
, '@');
543 if (cp
== NULL
|| cp
== p
)
551 optind
= optreset
= 1;
557 /* Check that we got a host name. */
561 SSLeay_add_all_algorithms();
562 ERR_load_crypto_strings();
564 /* Initialize the command to execute on remote host. */
565 buffer_init(&command
);
568 * Save the command to execute on the remote host in a buffer. There
569 * is no limit on the length of the command, except by the maximum
570 * packet size. Also sets the tty flag if there is no command.
573 /* No command specified - execute shell on a tty. */
575 if (subsystem_flag
) {
577 "You must specify a subsystem to invoke.\n");
581 /* A command has been specified. Store it into the buffer. */
582 for (i
= 0; i
< ac
; i
++) {
584 buffer_append(&command
, " ", 1);
585 buffer_append(&command
, av
[i
], strlen(av
[i
]));
589 /* Cannot fork to background if no command. */
590 if (fork_after_authentication_flag
&& buffer_len(&command
) == 0 && !no_shell_flag
)
591 fatal("Cannot fork into background without a command to execute.");
593 /* Allocate a tty by default if no command specified. */
594 if (buffer_len(&command
) == 0)
600 /* Do not allocate a tty if stdin is not a tty. */
601 if ((!isatty(fileno(stdin
)) || stdin_null_flag
) && !force_tty_flag
) {
603 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
608 * Initialize "log" output. Since we are the client all output
609 * actually goes to stderr.
611 log_init(av
[0], options
.log_level
== -1 ? SYSLOG_LEVEL_INFO
: options
.log_level
,
612 SYSLOG_FACILITY_USER
, 1);
615 * Read per-user configuration file. Ignore the system wide config
616 * file if the user specifies a config file on the command line.
618 if (config
!= NULL
) {
619 if (!read_config_file(config
, host
, &options
, 0))
620 fatal("Can't open user config file %.100s: "
621 "%.100s", config
, strerror(errno
));
623 snprintf(buf
, sizeof buf
, "%.100s/%.100s", pw
->pw_dir
,
624 _PATH_SSH_USER_CONFFILE
);
625 (void)read_config_file(buf
, host
, &options
, 1);
627 /* Read systemwide configuration file after use config. */
628 (void)read_config_file(_PATH_HOST_CONFIG_FILE
, host
,
632 /* Fill configuration defaults. */
633 fill_default_options(&options
);
635 channel_set_af(options
.address_family
);
638 log_init(av
[0], options
.log_level
, SYSLOG_FACILITY_USER
, 1);
642 if (options
.user
== NULL
)
643 options
.user
= xstrdup(pw
->pw_name
);
645 if (options
.hostname
!= NULL
)
646 host
= options
.hostname
;
648 /* Find canonic host name. */
649 if (strchr(host
, '.') == 0) {
650 struct addrinfo hints
;
651 struct addrinfo
*ai
= NULL
;
653 memset(&hints
, 0, sizeof(hints
));
654 hints
.ai_family
= options
.address_family
;
655 hints
.ai_flags
= AI_CANONNAME
;
656 hints
.ai_socktype
= SOCK_STREAM
;
657 errgai
= getaddrinfo(host
, NULL
, &hints
, &ai
);
659 if (ai
->ai_canonname
!= NULL
)
660 host
= xstrdup(ai
->ai_canonname
);
665 /* force lowercase for hostkey matching */
666 if (options
.host_key_alias
!= NULL
) {
667 for (p
= options
.host_key_alias
; *p
; p
++)
669 *p
= (char)tolower(*p
);
672 /* Get default port if port has not been set. */
673 if (options
.port
== 0) {
674 sp
= getservbyname(SSH_SERVICE_NAME
, "tcp");
675 options
.port
= sp
? ntohs(sp
->s_port
) : SSH_DEFAULT_PORT
;
678 if (options
.proxy_command
!= NULL
&&
679 strcmp(options
.proxy_command
, "none") == 0) {
680 xfree(options
.proxy_command
);
681 options
.proxy_command
= NULL
;
683 if (options
.control_path
!= NULL
&&
684 strcmp(options
.control_path
, "none") == 0) {
685 xfree(options
.control_path
);
686 options
.control_path
= NULL
;
689 if (options
.control_path
!= NULL
) {
690 char thishost
[NI_MAXHOST
];
692 if (gethostname(thishost
, sizeof(thishost
)) == -1)
693 fatal("gethostname: %s", strerror(errno
));
694 snprintf(buf
, sizeof(buf
), "%d", options
.port
);
695 cp
= tilde_expand_filename(options
.control_path
,
697 xfree(options
.control_path
);
698 options
.control_path
= percent_expand(cp
, "p", buf
, "h", host
,
699 "r", options
.user
, "l", thishost
, (char *)NULL
);
702 if (mux_command
!= 0 && options
.control_path
== NULL
)
703 fatal("No ControlPath specified for \"-O\" command");
704 if (options
.control_path
!= NULL
)
705 control_client(options
.control_path
);
707 timeout_ms
= options
.connection_timeout
* 1000;
709 /* Open a connection to the remote host. */
710 if (ssh_connect(host
, &hostaddr
, options
.port
,
711 options
.address_family
, options
.connection_attempts
, &timeout_ms
,
712 options
.tcp_keep_alive
,
714 options
.use_privileged_port
,
716 original_effective_uid
== 0 && options
.use_privileged_port
,
718 options
.proxy_command
) != 0)
722 debug3("timeout: %d ms remain after connect", timeout_ms
);
725 * If we successfully made the connection, load the host private key
726 * in case we will need it later for combined rsa-rhosts
727 * authentication. This must be done before releasing extra
728 * privileges, because the file is only readable by root.
729 * If we cannot access the private keys, load the public keys
730 * instead and try to execute the ssh-keysign helper instead.
732 sensitive_data
.nkeys
= 0;
733 sensitive_data
.keys
= NULL
;
734 sensitive_data
.external_keysign
= 0;
735 if (options
.rhosts_rsa_authentication
||
736 options
.hostbased_authentication
) {
737 sensitive_data
.nkeys
= 3;
738 sensitive_data
.keys
= xcalloc(sensitive_data
.nkeys
,
742 sensitive_data
.keys
[0] = key_load_private_type(KEY_RSA1
,
743 _PATH_HOST_KEY_FILE
, "", NULL
, NULL
);
744 sensitive_data
.keys
[1] = key_load_private_type(KEY_DSA
,
745 _PATH_HOST_DSA_KEY_FILE
, "", NULL
, NULL
);
746 sensitive_data
.keys
[2] = key_load_private_type(KEY_RSA
,
747 _PATH_HOST_RSA_KEY_FILE
, "", NULL
, NULL
);
750 if (options
.hostbased_authentication
== 1 &&
751 sensitive_data
.keys
[0] == NULL
&&
752 sensitive_data
.keys
[1] == NULL
&&
753 sensitive_data
.keys
[2] == NULL
) {
754 sensitive_data
.keys
[1] = key_load_public(
755 _PATH_HOST_DSA_KEY_FILE
, NULL
);
756 sensitive_data
.keys
[2] = key_load_public(
757 _PATH_HOST_RSA_KEY_FILE
, NULL
);
758 sensitive_data
.external_keysign
= 1;
762 * Get rid of any extra privileges that we may have. We will no
763 * longer need them. Also, extra privileges could make it very hard
764 * to read identity files and other non-world-readable files from the
765 * user's home directory if it happens to be on a NFS volume where
766 * root is mapped to nobody.
768 if (original_effective_uid
== 0) {
770 permanently_set_uid(pw
);
774 * Now that we are back to our own permissions, create ~/.ssh
775 * directory if it doesn't already exist.
777 snprintf(buf
, sizeof buf
, "%.100s%s%.100s", pw
->pw_dir
, strcmp(pw
->pw_dir
, "/") ? "/" : "", _PATH_SSH_USER_DIR
);
778 if (stat(buf
, &st
) < 0)
779 if (mkdir(buf
, 0700) < 0)
780 error("Could not create directory '%.200s'.", buf
);
782 /* load options.identity_files */
783 load_public_identity_files();
785 /* Expand ~ in known host file names. */
787 options
.system_hostfile
=
788 tilde_expand_filename(options
.system_hostfile
, original_real_uid
);
789 options
.user_hostfile
=
790 tilde_expand_filename(options
.user_hostfile
, original_real_uid
);
791 options
.system_hostfile2
=
792 tilde_expand_filename(options
.system_hostfile2
, original_real_uid
);
793 options
.user_hostfile2
=
794 tilde_expand_filename(options
.user_hostfile2
, original_real_uid
);
796 signal(SIGPIPE
, SIG_IGN
); /* ignore SIGPIPE early */
798 /* Log into the remote system. This never returns if the login fails. */
799 ssh_login(&sensitive_data
, host
, (struct sockaddr
*)&hostaddr
,
802 /* We no longer need the private host keys. Clear them now. */
803 if (sensitive_data
.nkeys
!= 0) {
804 for (i
= 0; i
< sensitive_data
.nkeys
; i
++) {
805 if (sensitive_data
.keys
[i
] != NULL
) {
806 /* Destroys contents safely */
807 debug3("clear hostkey %d", i
);
808 key_free(sensitive_data
.keys
[i
]);
809 sensitive_data
.keys
[i
] = NULL
;
812 xfree(sensitive_data
.keys
);
814 for (i
= 0; i
< options
.num_identity_files
; i
++) {
815 if (options
.identity_files
[i
]) {
816 xfree(options
.identity_files
[i
]);
817 options
.identity_files
[i
] = NULL
;
819 if (options
.identity_keys
[i
]) {
820 key_free(options
.identity_keys
[i
]);
821 options
.identity_keys
[i
] = NULL
;
825 exit_status
= compat20
? ssh_session2() : ssh_session();
828 if (options
.control_path
!= NULL
&& control_fd
!= -1)
829 unlink(options
.control_path
);
832 * Send SIGHUP to proxy command if used. We don't wait() in
833 * case it hangs and instead rely on init to reap the child
835 if (proxy_command_pid
> 1)
836 kill(proxy_command_pid
, SIGHUP
);
842 ssh_init_forwarding(void)
847 /* Initiate local TCP/IP port forwardings. */
848 for (i
= 0; i
< options
.num_local_forwards
; i
++) {
849 debug("Local connections to %.200s:%d forwarded to remote "
851 (options
.local_forwards
[i
].listen_host
== NULL
) ?
852 (options
.gateway_ports
? "*" : "LOCALHOST") :
853 options
.local_forwards
[i
].listen_host
,
854 options
.local_forwards
[i
].listen_port
,
855 options
.local_forwards
[i
].connect_host
,
856 options
.local_forwards
[i
].connect_port
);
857 success
+= channel_setup_local_fwd_listener(
858 options
.local_forwards
[i
].listen_host
,
859 options
.local_forwards
[i
].listen_port
,
860 options
.local_forwards
[i
].connect_host
,
861 options
.local_forwards
[i
].connect_port
,
862 options
.gateway_ports
);
864 if (i
> 0 && success
!= i
&& options
.exit_on_forward_failure
)
865 fatal("Could not request local forwarding.");
866 if (i
> 0 && success
== 0)
867 error("Could not request local forwarding.");
869 /* Initiate remote TCP/IP port forwardings. */
870 for (i
= 0; i
< options
.num_remote_forwards
; i
++) {
871 debug("Remote connections from %.200s:%d forwarded to "
872 "local address %.200s:%d",
873 (options
.remote_forwards
[i
].listen_host
== NULL
) ?
874 "LOCALHOST" : options
.remote_forwards
[i
].listen_host
,
875 options
.remote_forwards
[i
].listen_port
,
876 options
.remote_forwards
[i
].connect_host
,
877 options
.remote_forwards
[i
].connect_port
);
878 if (channel_request_remote_forwarding(
879 options
.remote_forwards
[i
].listen_host
,
880 options
.remote_forwards
[i
].listen_port
,
881 options
.remote_forwards
[i
].connect_host
,
882 options
.remote_forwards
[i
].connect_port
) < 0) {
883 if (options
.exit_on_forward_failure
)
884 fatal("Could not request remote forwarding.");
886 logit("Warning: Could not request remote "
891 /* Initiate tunnel forwarding. */
892 if (options
.tun_open
!= SSH_TUNMODE_NO
) {
893 if (client_request_tun_fwd(options
.tun_open
,
894 options
.tun_local
, options
.tun_remote
) == -1) {
895 if (options
.exit_on_forward_failure
)
896 fatal("Could not request tunnel forwarding.");
898 error("Could not request tunnel forwarding.");
904 check_agent_present(void)
906 if (options
.forward_agent
) {
907 /* Clear agent forwarding if we don't have an agent. */
908 if (!ssh_agent_present())
909 options
.forward_agent
= 0;
923 /* Enable compression if requested. */
924 if (options
.compression
) {
925 debug("Requesting compression at level %d.", options
.compression_level
);
927 if (options
.compression_level
< 1 || options
.compression_level
> 9)
928 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
930 /* Send the request. */
931 packet_start(SSH_CMSG_REQUEST_COMPRESSION
);
932 packet_put_int(options
.compression_level
);
935 type
= packet_read();
936 if (type
== SSH_SMSG_SUCCESS
)
937 packet_start_compression(options
.compression_level
);
938 else if (type
== SSH_SMSG_FAILURE
)
939 logit("Warning: Remote host refused compression.");
941 packet_disconnect("Protocol error waiting for compression response.");
943 /* Allocate a pseudo tty if appropriate. */
945 debug("Requesting pty.");
947 /* Start the packet. */
948 packet_start(SSH_CMSG_REQUEST_PTY
);
950 /* Store TERM in the packet. There is no limit on the
951 length of the string. */
955 packet_put_cstring(cp
);
957 /* Store window size in the packet. */
958 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) < 0)
959 memset(&ws
, 0, sizeof(ws
));
960 packet_put_int((u_int
)ws
.ws_row
);
961 packet_put_int((u_int
)ws
.ws_col
);
962 packet_put_int((u_int
)ws
.ws_xpixel
);
963 packet_put_int((u_int
)ws
.ws_ypixel
);
965 /* Store tty modes in the packet. */
966 tty_make_modes(fileno(stdin
), NULL
);
968 /* Send the packet, and wait for it to leave. */
972 /* Read response from the server. */
973 type
= packet_read();
974 if (type
== SSH_SMSG_SUCCESS
) {
977 } else if (type
== SSH_SMSG_FAILURE
)
978 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
980 packet_disconnect("Protocol error waiting for pty request response.");
982 /* Request X11 forwarding if enabled and DISPLAY is set. */
983 display
= getenv("DISPLAY");
984 if (options
.forward_x11
&& display
!= NULL
) {
986 /* Get reasonable local authentication information. */
987 client_x11_get_proto(display
, options
.xauth_location
,
988 options
.forward_x11_trusted
, &proto
, &data
);
989 /* Request forwarding with authentication spoofing. */
990 debug("Requesting X11 forwarding with authentication spoofing.");
991 x11_request_forwarding_with_spoofing(0, display
, proto
, data
);
993 /* Read response from the server. */
994 type
= packet_read();
995 if (type
== SSH_SMSG_SUCCESS
) {
997 } else if (type
== SSH_SMSG_FAILURE
) {
998 logit("Warning: Remote host denied X11 forwarding.");
1000 packet_disconnect("Protocol error waiting for X11 forwarding");
1003 /* Tell the packet module whether this is an interactive session. */
1004 packet_set_interactive(interactive
);
1006 /* Request authentication agent forwarding if appropriate. */
1007 check_agent_present();
1009 if (options
.forward_agent
) {
1010 debug("Requesting authentication agent forwarding.");
1011 auth_request_forwarding();
1013 /* Read response from the server. */
1014 type
= packet_read();
1016 if (type
!= SSH_SMSG_SUCCESS
)
1017 logit("Warning: Remote host denied authentication agent forwarding.");
1020 /* Initiate port forwardings. */
1021 ssh_init_forwarding();
1023 /* Execute a local command */
1024 if (options
.local_command
!= NULL
&&
1025 options
.permit_local_command
)
1026 ssh_local_cmd(options
.local_command
);
1028 /* If requested, let ssh continue in the background. */
1029 if (fork_after_authentication_flag
)
1030 if (daemon(1, 1) < 0)
1031 fatal("daemon() failed: %.200s", strerror(errno
));
1034 * If a command was specified on the command line, execute the
1035 * command now. Otherwise request the server to start a shell.
1037 if (buffer_len(&command
) > 0) {
1038 int len
= buffer_len(&command
);
1041 debug("Sending command: %.*s", len
, (u_char
*)buffer_ptr(&command
));
1042 packet_start(SSH_CMSG_EXEC_CMD
);
1043 packet_put_string(buffer_ptr(&command
), buffer_len(&command
));
1045 packet_write_wait();
1047 debug("Requesting shell.");
1048 packet_start(SSH_CMSG_EXEC_SHELL
);
1050 packet_write_wait();
1053 /* Enter the interactive session. */
1054 return client_loop(have_tty
, tty_flag
?
1055 options
.escape_char
: SSH_ESCAPECHAR_NONE
, 0);
1059 ssh_subsystem_reply(int type
, u_int32_t seq
, void *ctxt
)
1063 id
= packet_get_int();
1064 len
= buffer_len(&command
);
1068 if (type
== SSH2_MSG_CHANNEL_FAILURE
)
1069 fatal("Request for subsystem '%.*s' failed on channel %d",
1070 len
, (u_char
*)buffer_ptr(&command
), id
);
1074 client_global_request_reply_fwd(int type
, u_int32_t seq
, void *ctxt
)
1078 i
= client_global_request_id
++;
1079 if (i
>= options
.num_remote_forwards
)
1081 debug("remote forward %s for: listen %d, connect %s:%d",
1082 type
== SSH2_MSG_REQUEST_SUCCESS
? "success" : "failure",
1083 options
.remote_forwards
[i
].listen_port
,
1084 options
.remote_forwards
[i
].connect_host
,
1085 options
.remote_forwards
[i
].connect_port
);
1086 if (type
== SSH2_MSG_REQUEST_FAILURE
) {
1087 if (options
.exit_on_forward_failure
)
1088 fatal("Error: remote port forwarding failed for "
1090 options
.remote_forwards
[i
].listen_port
);
1092 logit("Warning: remote port forwarding failed for "
1094 options
.remote_forwards
[i
].listen_port
);
1099 ssh_control_listener(void)
1101 struct sockaddr_un addr
;
1105 if (options
.control_path
== NULL
||
1106 options
.control_master
== SSHCTL_MASTER_NO
)
1109 debug("setting up multiplex master socket");
1111 memset(&addr
, '\0', sizeof(addr
));
1112 addr
.sun_family
= AF_UNIX
;
1113 addr_len
= offsetof(struct sockaddr_un
, sun_path
) +
1114 strlen(options
.control_path
) + 1;
1116 if (strlcpy(addr
.sun_path
, options
.control_path
,
1117 sizeof(addr
.sun_path
)) >= sizeof(addr
.sun_path
))
1118 fatal("ControlPath too long");
1120 if ((control_fd
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
1121 fatal("%s socket(): %s", __func__
, strerror(errno
));
1123 old_umask
= umask(0177);
1124 if (bind(control_fd
, (struct sockaddr
*)&addr
, addr_len
) == -1) {
1126 if (errno
== EINVAL
|| errno
== EADDRINUSE
)
1127 fatal("ControlSocket %s already exists",
1128 options
.control_path
);
1130 fatal("%s bind(): %s", __func__
, strerror(errno
));
1134 if (listen(control_fd
, 64) == -1)
1135 fatal("%s listen(): %s", __func__
, strerror(errno
));
1137 set_nonblock(control_fd
);
1140 /* request pty/x11/agent/tcpfwd/shell for channel */
1142 ssh_session2_setup(int id
, void *arg
)
1144 extern char **environ
;
1145 const char *display
;
1146 int interactive
= tty_flag
;
1148 display
= getenv("DISPLAY");
1149 if (options
.forward_x11
&& display
!= NULL
) {
1151 /* Get reasonable local authentication information. */
1152 client_x11_get_proto(display
, options
.xauth_location
,
1153 options
.forward_x11_trusted
, &proto
, &data
);
1154 /* Request forwarding with authentication spoofing. */
1155 debug("Requesting X11 forwarding with authentication spoofing.");
1156 x11_request_forwarding_with_spoofing(id
, display
, proto
, data
);
1158 /* XXX wait for reply */
1161 check_agent_present();
1162 if (options
.forward_agent
) {
1163 debug("Requesting authentication agent forwarding.");
1164 channel_request_start(id
, "auth-agent-req@openssh.com", 0);
1168 client_session2_setup(id
, tty_flag
, subsystem_flag
, getenv("TERM"),
1169 NULL
, fileno(stdin
), &command
, environ
, &ssh_subsystem_reply
);
1171 packet_set_interactive(interactive
);
1174 /* open new channel for a session */
1176 ssh_session2_open(void)
1179 int window
, packetmax
, in
, out
, err
;
1181 if (stdin_null_flag
) {
1182 in
= open(_PATH_DEVNULL
, O_RDONLY
);
1184 in
= dup(STDIN_FILENO
);
1186 out
= dup(STDOUT_FILENO
);
1187 err
= dup(STDERR_FILENO
);
1189 if (in
< 0 || out
< 0 || err
< 0)
1190 fatal("dup() in/out/err failed");
1192 /* enable nonblocking unless tty */
1200 window
= CHAN_SES_WINDOW_DEFAULT
;
1201 packetmax
= CHAN_SES_PACKET_DEFAULT
;
1207 "session", SSH_CHANNEL_OPENING
, in
, out
, err
,
1208 window
, packetmax
, CHAN_EXTENDED_WRITE
,
1209 "client-session", /*nonblock*/0);
1211 debug3("ssh_session2_open: channel_new: %d", c
->self
);
1213 channel_send_open(c
->self
);
1215 channel_register_confirm(c
->self
, ssh_session2_setup
, NULL
);
1225 /* XXX should be pre-session */
1226 ssh_init_forwarding();
1228 if (!no_shell_flag
|| (datafellows
& SSH_BUG_DUMMYCHAN
))
1229 id
= ssh_session2_open();
1231 /* Execute a local command */
1232 if (options
.local_command
!= NULL
&&
1233 options
.permit_local_command
)
1234 ssh_local_cmd(options
.local_command
);
1236 /* Start listening for multiplex clients */
1237 ssh_control_listener();
1239 /* If requested, let ssh continue in the background. */
1240 if (fork_after_authentication_flag
)
1241 if (daemon(1, 1) < 0)
1242 fatal("daemon() failed: %.200s", strerror(errno
));
1244 return client_loop(tty_flag
, tty_flag
?
1245 options
.escape_char
: SSH_ESCAPECHAR_NONE
, id
);
1249 load_public_identity_files(void)
1251 char *filename
, *cp
, thishost
[NI_MAXHOST
];
1252 char *pwdir
= NULL
, *pwname
= NULL
;
1259 if (options
.smartcard_device
!= NULL
&&
1260 options
.num_identity_files
< SSH_MAX_IDENTITY_FILES
&&
1261 (keys
= sc_get_keys(options
.smartcard_device
, NULL
)) != NULL
) {
1263 for (i
= 0; keys
[i
] != NULL
; i
++) {
1265 memmove(&options
.identity_files
[1], &options
.identity_files
[0],
1266 sizeof(char *) * (SSH_MAX_IDENTITY_FILES
- 1));
1267 memmove(&options
.identity_keys
[1], &options
.identity_keys
[0],
1268 sizeof(Key
*) * (SSH_MAX_IDENTITY_FILES
- 1));
1269 options
.num_identity_files
++;
1270 options
.identity_keys
[0] = keys
[i
];
1271 options
.identity_files
[0] = sc_get_key_label(keys
[i
]);
1273 if (options
.num_identity_files
> SSH_MAX_IDENTITY_FILES
)
1274 options
.num_identity_files
= SSH_MAX_IDENTITY_FILES
;
1278 #endif /* SMARTCARD */
1279 if ((pw
= getpwuid(original_real_uid
)) == NULL
)
1280 fatal("load_public_identity_files: getpwuid failed");
1281 pwname
= xstrdup(pw
->pw_name
);
1282 pwdir
= xstrdup(pw
->pw_dir
);
1283 if (gethostname(thishost
, sizeof(thishost
)) == -1)
1284 fatal("load_public_identity_files: gethostname: %s",
1286 for (; i
< options
.num_identity_files
; i
++) {
1287 cp
= tilde_expand_filename(options
.identity_files
[i
],
1289 filename
= percent_expand(cp
, "d", pwdir
,
1290 "u", pwname
, "l", thishost
, "h", host
,
1291 "r", options
.user
, (char *)NULL
);
1293 public = key_load_public(filename
, NULL
);
1294 debug("identity file %s type %d", filename
,
1295 public ? public->type
: -1);
1296 xfree(options
.identity_files
[i
]);
1297 options
.identity_files
[i
] = filename
;
1298 options
.identity_keys
[i
] = public;
1300 bzero(pwname
, strlen(pwname
));
1302 bzero(pwdir
, strlen(pwdir
));
1307 control_client_sighandler(int signo
)
1309 control_client_terminate
= signo
;
1313 control_client_sigrelay(int signo
)
1315 int save_errno
= errno
;
1317 if (control_server_pid
> 1)
1318 kill(control_server_pid
, signo
);
1324 env_permitted(char *env
)
1327 char name
[1024], *cp
;
1329 if ((cp
= strchr(env
, '=')) == NULL
|| cp
== env
)
1331 ret
= snprintf(name
, sizeof(name
), "%.*s", (int)(cp
- env
), env
);
1332 if (ret
<= 0 || (size_t)ret
>= sizeof(name
))
1333 fatal("env_permitted: name '%.100s...' too long", env
);
1335 for (i
= 0; i
< options
.num_send_env
; i
++)
1336 if (match_pattern(name
, options
.send_env
[i
]))
1343 control_client(const char *path
)
1345 struct sockaddr_un addr
;
1346 int i
, r
, fd
, sock
, exitval
[2], num_env
, addr_len
;
1349 extern char **environ
;
1352 if (mux_command
== 0)
1353 mux_command
= SSHMUX_COMMAND_OPEN
;
1355 switch (options
.control_master
) {
1356 case SSHCTL_MASTER_AUTO
:
1357 case SSHCTL_MASTER_AUTO_ASK
:
1358 debug("auto-mux: Trying existing master");
1360 case SSHCTL_MASTER_NO
:
1366 memset(&addr
, '\0', sizeof(addr
));
1367 addr
.sun_family
= AF_UNIX
;
1368 addr_len
= offsetof(struct sockaddr_un
, sun_path
) +
1371 if (strlcpy(addr
.sun_path
, path
,
1372 sizeof(addr
.sun_path
)) >= sizeof(addr
.sun_path
))
1373 fatal("ControlPath too long");
1375 if ((sock
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
1376 fatal("%s socket(): %s", __func__
, strerror(errno
));
1378 if (connect(sock
, (struct sockaddr
*)&addr
, addr_len
) == -1) {
1379 if (mux_command
!= SSHMUX_COMMAND_OPEN
) {
1380 fatal("Control socket connect(%.100s): %s", path
,
1383 if (errno
== ENOENT
)
1384 debug("Control socket \"%.100s\" does not exist", path
);
1386 error("Control socket connect(%.100s): %s", path
,
1393 if (stdin_null_flag
) {
1394 if ((fd
= open(_PATH_DEVNULL
, O_RDONLY
)) == -1)
1395 fatal("open(/dev/null): %s", strerror(errno
));
1396 if (dup2(fd
, STDIN_FILENO
) == -1)
1397 fatal("dup2: %s", strerror(errno
));
1398 if (fd
> STDERR_FILENO
)
1402 term
= getenv("TERM");
1406 flags
|= SSHMUX_FLAG_TTY
;
1408 flags
|= SSHMUX_FLAG_SUBSYS
;
1409 if (options
.forward_x11
)
1410 flags
|= SSHMUX_FLAG_X11_FWD
;
1411 if (options
.forward_agent
)
1412 flags
|= SSHMUX_FLAG_AGENT_FWD
;
1414 signal(SIGPIPE
, SIG_IGN
);
1418 /* Send our command to server */
1419 buffer_put_int(&m
, mux_command
);
1420 buffer_put_int(&m
, flags
);
1421 if (ssh_msg_send(sock
, SSHMUX_VER
, &m
) == -1)
1422 fatal("%s: msg_send", __func__
);
1425 /* Get authorisation status and PID of controlee */
1426 if (ssh_msg_recv(sock
, &m
) == -1)
1427 fatal("%s: msg_recv", __func__
);
1428 if (buffer_get_char(&m
) != SSHMUX_VER
)
1429 fatal("%s: wrong version", __func__
);
1430 if (buffer_get_int(&m
) != 1)
1431 fatal("Connection to master denied");
1432 control_server_pid
= buffer_get_int(&m
);
1436 switch (mux_command
) {
1437 case SSHMUX_COMMAND_ALIVE_CHECK
:
1438 fprintf(stderr
, "Master running (pid=%d)\r\n",
1439 control_server_pid
);
1441 case SSHMUX_COMMAND_TERMINATE
:
1442 fprintf(stderr
, "Exit request sent.\r\n");
1444 case SSHMUX_COMMAND_OPEN
:
1445 /* continue below */
1448 fatal("silly mux_command %d", mux_command
);
1451 /* SSHMUX_COMMAND_OPEN */
1452 buffer_put_cstring(&m
, term
? term
: "");
1453 buffer_append(&command
, "\0", 1);
1454 buffer_put_cstring(&m
, buffer_ptr(&command
));
1456 if (options
.num_send_env
== 0 || environ
== NULL
) {
1457 buffer_put_int(&m
, 0);
1459 /* Pass environment */
1461 for (i
= 0; environ
[i
] != NULL
; i
++)
1462 if (env_permitted(environ
[i
]))
1463 num_env
++; /* Count */
1465 buffer_put_int(&m
, num_env
);
1467 for (i
= 0; environ
[i
] != NULL
&& num_env
>= 0; i
++)
1468 if (env_permitted(environ
[i
])) {
1470 buffer_put_cstring(&m
, environ
[i
]);
1474 if (ssh_msg_send(sock
, SSHMUX_VER
, &m
) == -1)
1475 fatal("%s: msg_send", __func__
);
1477 if (mm_send_fd(sock
, STDIN_FILENO
) == -1 ||
1478 mm_send_fd(sock
, STDOUT_FILENO
) == -1 ||
1479 mm_send_fd(sock
, STDERR_FILENO
) == -1)
1480 fatal("%s: send fds failed", __func__
);
1482 /* Wait for reply, so master has a chance to gather ttymodes */
1484 if (ssh_msg_recv(sock
, &m
) == -1)
1485 fatal("%s: msg_recv", __func__
);
1486 if (buffer_get_char(&m
) != SSHMUX_VER
)
1487 fatal("%s: wrong version", __func__
);
1490 signal(SIGHUP
, control_client_sighandler
);
1491 signal(SIGINT
, control_client_sighandler
);
1492 signal(SIGTERM
, control_client_sighandler
);
1493 signal(SIGWINCH
, control_client_sigrelay
);
1499 * Stick around until the controlee closes the client_fd.
1500 * Before it does, it is expected to write this process' exit
1501 * value (one int). This process must read the value and wait for
1502 * the closure of the client_fd; if this one closes early, the
1503 * multiplex master will terminate early too (possibly losing data).
1506 for (i
= 0; !control_client_terminate
&& i
< (int)sizeof(exitval
);) {
1507 r
= read(sock
, (char *)exitval
+ i
, sizeof(exitval
) - i
);
1509 debug2("Received EOF from master");
1515 fatal("%s: read %s", __func__
, strerror(errno
));
1522 if (i
> (int)sizeof(int))
1523 fatal("%s: master returned too much data (%d > %lu)",
1524 __func__
, i
, sizeof(int));
1525 if (control_client_terminate
) {
1526 debug2("Exiting on signal %d", control_client_terminate
);
1528 } else if (i
< (int)sizeof(int)) {
1529 debug2("Control master terminated unexpectedly");
1532 debug2("Received exit status from master %d", exitval
[0]);
1534 if (tty_flag
&& options
.log_level
!= SYSLOG_LEVEL_QUIET
)
1535 fprintf(stderr
, "Shared connection to %s closed.\r\n", host
);