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>
88 #include "pathnames.h"
90 #include "clientloop.h"
93 #include "sshconnect.h"
100 #include "monitor_fdpass.h"
108 extern char *__progname
;
110 /* Flag indicating whether debug mode is on. This can be set on the command line. */
113 /* Flag indicating whether a tty should be allocated */
116 int force_tty_flag
= 0;
118 /* don't exec a shell */
119 int no_shell_flag
= 0;
122 * Flag indicating that nothing should be read from stdin. This can be set
123 * on the command line.
125 int stdin_null_flag
= 0;
128 * Flag indicating that ssh should fork after authentication. This is useful
129 * so that the passphrase can be entered manually, and then ssh goes to the
132 int fork_after_authentication_flag
= 0;
135 * General data structure for command line options and options configurable
136 * in configuration files. See readconf.h.
140 /* optional user configfile */
144 * Name of the host we are connecting to. This is the name given on the
145 * command line, or the HostName specified for the user-supplied name in a
146 * configuration file.
150 /* socket address the host resolves to */
151 struct sockaddr_storage hostaddr
;
153 /* Private host keys. */
154 Sensitive sensitive_data
;
156 /* Original real UID. */
157 uid_t original_real_uid
;
158 uid_t original_effective_uid
;
160 /* command to be executed */
163 /* Should we execute a command or invoke a subsystem? */
164 int subsystem_flag
= 0;
166 /* # of replies received for global requests */
167 static int client_global_request_id
= 0;
169 /* pid of proxycommand child process */
170 pid_t proxy_command_pid
= 0;
172 /* fd to control socket */
175 /* Multiplexing control command */
176 static u_int mux_command
= 0;
178 /* Only used in control client mode */
179 volatile sig_atomic_t control_client_terminate
= 0;
180 u_int control_server_pid
= 0;
182 /* Prints a help message to the user. This function never returns. */
188 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
189 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
190 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
191 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
192 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
193 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
198 static int ssh_session(void);
199 static int ssh_session2(void);
200 static void load_public_identity_files(void);
201 static void control_client(const char *path
);
204 * Main program for the ssh client.
207 main(int ac
, char **av
)
209 int i
, opt
, exit_status
;
210 char *p
, *cp
, *line
, buf
[256];
213 int dummy
, timeout_ms
;
214 extern int optind
, optreset
;
219 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
222 __progname
= ssh_get_progname(av
[0]);
226 * Save the original real uid. It will be needed later (uid-swapping
227 * may clobber the real uid).
229 original_real_uid
= getuid();
230 original_effective_uid
= geteuid();
233 * Use uid-swapping to give up root privileges for the duration of
234 * option processing. We will re-instantiate the rights when we are
235 * ready to create the privileged port, and will permanently drop
236 * them when the port has been created (actually, when the connection
237 * has been made, as we may need to create the port several times).
241 #ifdef HAVE_SETRLIMIT
242 /* If we are installed setuid root be careful to not drop core. */
243 if (original_real_uid
!= original_effective_uid
) {
245 rlim
.rlim_cur
= rlim
.rlim_max
= 0;
246 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
247 fatal("setrlimit failed: %.100s", strerror(errno
));
251 pw
= getpwuid(original_real_uid
);
253 logit("You don't exist, go away!");
256 /* Take a copy of the returned structure. */
260 * Set our umask to something reasonable, as some files are created
261 * with the default umask. This will make them world-readable but
262 * writable only by the owner, which is ok for all files for which we
263 * don't set the modes explicitly.
267 /* Initialize option structure to indicate that no values have been set. */
268 initialize_options(&options
);
270 /* Parse command-line arguments. */
274 while ((opt
= getopt(ac
, av
,
275 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:KL:MNO:PR:S:TVw:XY")) != -1) {
278 options
.protocol
= SSH_PROTO_1
;
281 options
.protocol
= SSH_PROTO_2
;
284 options
.address_family
= AF_INET
;
287 options
.address_family
= AF_INET6
;
293 fork_after_authentication_flag
= 1;
297 options
.forward_x11
= 0;
300 options
.forward_x11
= 1;
303 options
.forward_x11
= 1;
304 options
.forward_x11_trusted
= 1;
307 options
.gateway_ports
= 1;
310 if (strcmp(optarg
, "check") == 0)
311 mux_command
= SSHMUX_COMMAND_ALIVE_CHECK
;
312 else if (strcmp(optarg
, "exit") == 0)
313 mux_command
= SSHMUX_COMMAND_TERMINATE
;
315 fatal("Invalid multiplex command.");
317 case 'P': /* deprecated */
318 options
.use_privileged_port
= 0;
321 options
.forward_agent
= 0;
324 options
.forward_agent
= 1;
327 options
.gss_deleg_creds
= 0;
330 options
.gss_authentication
= 1;
331 options
.gss_deleg_creds
= 1;
334 if (stat(optarg
, &st
) < 0) {
335 fprintf(stderr
, "Warning: Identity file %s "
336 "not accessible: %s.\n", optarg
,
340 if (options
.num_identity_files
>=
341 SSH_MAX_IDENTITY_FILES
)
342 fatal("Too many identity files specified "
343 "(max %d)", SSH_MAX_IDENTITY_FILES
);
344 options
.identity_files
[options
.num_identity_files
++] =
349 options
.smartcard_device
= xstrdup(optarg
);
351 fprintf(stderr
, "no support for smartcards.\n");
360 if (debug_flag
== 0) {
362 options
.log_level
= SYSLOG_LEVEL_DEBUG1
;
364 if (options
.log_level
< SYSLOG_LEVEL_DEBUG3
)
370 fprintf(stderr
, "%s, %s\n",
371 SSH_RELEASE
, SSLeay_version(SSLEAY_VERSION
));
376 if (options
.tun_open
== -1)
377 options
.tun_open
= SSH_TUNMODE_DEFAULT
;
378 options
.tun_local
= a2tun(optarg
, &options
.tun_remote
);
379 if (options
.tun_local
== SSH_TUNID_ERR
) {
380 fprintf(stderr
, "Bad tun device '%s'\n", optarg
);
385 options
.log_level
= SYSLOG_LEVEL_QUIET
;
388 if (optarg
[0] == '^' && optarg
[2] == 0 &&
389 (u_char
) optarg
[1] >= 64 &&
390 (u_char
) optarg
[1] < 128)
391 options
.escape_char
= (u_char
) optarg
[1] & 31;
392 else if (strlen(optarg
) == 1)
393 options
.escape_char
= (u_char
) optarg
[0];
394 else if (strcmp(optarg
, "none") == 0)
395 options
.escape_char
= SSH_ESCAPECHAR_NONE
;
397 fprintf(stderr
, "Bad escape character '%s'.\n",
403 if (ciphers_valid(optarg
)) {
405 options
.ciphers
= xstrdup(optarg
);
406 options
.cipher
= SSH_CIPHER_INVALID
;
409 options
.cipher
= cipher_number(optarg
);
410 if (options
.cipher
== -1) {
412 "Unknown cipher type '%s'\n",
416 if (options
.cipher
== SSH_CIPHER_3DES
)
417 options
.ciphers
= "3des-cbc";
418 else if (options
.cipher
== SSH_CIPHER_BLOWFISH
)
419 options
.ciphers
= "blowfish-cbc";
421 options
.ciphers
= (char *)-1;
425 if (mac_valid(optarg
))
426 options
.macs
= xstrdup(optarg
);
428 fprintf(stderr
, "Unknown mac type '%s'\n",
434 if (options
.control_master
== SSHCTL_MASTER_YES
)
435 options
.control_master
= SSHCTL_MASTER_ASK
;
437 options
.control_master
= SSHCTL_MASTER_YES
;
440 options
.port
= a2port(optarg
);
441 if (options
.port
== 0) {
442 fprintf(stderr
, "Bad port '%s'\n", optarg
);
447 options
.user
= optarg
;
451 if (parse_forward(&fwd
, optarg
))
452 add_local_forward(&options
, &fwd
);
455 "Bad local forwarding specification '%s'\n",
462 if (parse_forward(&fwd
, optarg
)) {
463 add_remote_forward(&options
, &fwd
);
466 "Bad remote forwarding specification "
473 cp
= p
= xstrdup(optarg
);
474 memset(&fwd
, '\0', sizeof(fwd
));
475 fwd
.connect_host
= "socks";
476 if ((fwd
.listen_host
= hpdelim(&cp
)) == NULL
) {
477 fprintf(stderr
, "Bad dynamic forwarding "
478 "specification '%.100s'\n", optarg
);
482 fwd
.listen_port
= a2port(cp
);
483 fwd
.listen_host
= cleanhostname(fwd
.listen_host
);
485 fwd
.listen_port
= a2port(fwd
.listen_host
);
486 fwd
.listen_host
= NULL
;
489 if (fwd
.listen_port
== 0) {
490 fprintf(stderr
, "Bad dynamic port '%s'\n",
494 add_local_forward(&options
, &fwd
);
499 options
.compression
= 1;
510 line
= xstrdup(optarg
);
511 if (process_config_line(&options
, host
? host
: "",
512 line
, "command-line", 0, &dummy
) != 0)
520 if (options
.control_path
!= NULL
)
521 free(options
.control_path
);
522 options
.control_path
= xstrdup(optarg
);
525 options
.bind_address
= optarg
;
538 if (ac
> 0 && !host
&& **av
!= '-') {
539 if (strrchr(*av
, '@')) {
541 cp
= strrchr(p
, '@');
542 if (cp
== NULL
|| cp
== p
)
550 optind
= optreset
= 1;
556 /* Check that we got a host name. */
560 SSLeay_add_all_algorithms();
561 ERR_load_crypto_strings();
563 /* Initialize the command to execute on remote host. */
564 buffer_init(&command
);
567 * Save the command to execute on the remote host in a buffer. There
568 * is no limit on the length of the command, except by the maximum
569 * packet size. Also sets the tty flag if there is no command.
572 /* No command specified - execute shell on a tty. */
574 if (subsystem_flag
) {
576 "You must specify a subsystem to invoke.\n");
580 /* A command has been specified. Store it into the buffer. */
581 for (i
= 0; i
< ac
; i
++) {
583 buffer_append(&command
, " ", 1);
584 buffer_append(&command
, av
[i
], strlen(av
[i
]));
588 /* Cannot fork to background if no command. */
589 if (fork_after_authentication_flag
&& buffer_len(&command
) == 0 && !no_shell_flag
)
590 fatal("Cannot fork into background without a command to execute.");
592 /* Allocate a tty by default if no command specified. */
593 if (buffer_len(&command
) == 0)
599 /* Do not allocate a tty if stdin is not a tty. */
600 if ((!isatty(fileno(stdin
)) || stdin_null_flag
) && !force_tty_flag
) {
602 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
607 * Initialize "log" output. Since we are the client all output
608 * actually goes to stderr.
610 log_init(av
[0], options
.log_level
== -1 ? SYSLOG_LEVEL_INFO
: options
.log_level
,
611 SYSLOG_FACILITY_USER
, 1);
614 * Read per-user configuration file. Ignore the system wide config
615 * file if the user specifies a config file on the command line.
617 if (config
!= NULL
) {
618 if (!read_config_file(config
, host
, &options
, 0))
619 fatal("Can't open user config file %.100s: "
620 "%.100s", config
, strerror(errno
));
622 snprintf(buf
, sizeof buf
, "%.100s/%.100s", pw
->pw_dir
,
623 _PATH_SSH_USER_CONFFILE
);
624 (void)read_config_file(buf
, host
, &options
, 1);
626 /* Read systemwide configuration file after use config. */
627 (void)read_config_file(_PATH_HOST_CONFIG_FILE
, host
,
631 /* Fill configuration defaults. */
632 fill_default_options(&options
);
634 channel_set_af(options
.address_family
);
637 log_init(av
[0], options
.log_level
, SYSLOG_FACILITY_USER
, 1);
641 if (options
.user
== NULL
)
642 options
.user
= xstrdup(pw
->pw_name
);
644 if (options
.hostname
!= NULL
)
645 host
= options
.hostname
;
647 /* force lowercase for hostkey matching */
648 if (options
.host_key_alias
!= NULL
) {
649 for (p
= options
.host_key_alias
; *p
; p
++)
651 *p
= (char)tolower(*p
);
654 /* Get default port if port has not been set. */
655 if (options
.port
== 0) {
656 sp
= getservbyname(SSH_SERVICE_NAME
, "tcp");
657 options
.port
= sp
? ntohs(sp
->s_port
) : SSH_DEFAULT_PORT
;
660 if (options
.proxy_command
!= NULL
&&
661 strcmp(options
.proxy_command
, "none") == 0) {
662 xfree(options
.proxy_command
);
663 options
.proxy_command
= NULL
;
665 if (options
.control_path
!= NULL
&&
666 strcmp(options
.control_path
, "none") == 0) {
667 xfree(options
.control_path
);
668 options
.control_path
= NULL
;
671 if (options
.control_path
!= NULL
) {
672 char thishost
[NI_MAXHOST
];
674 if (gethostname(thishost
, sizeof(thishost
)) == -1)
675 fatal("gethostname: %s", strerror(errno
));
676 snprintf(buf
, sizeof(buf
), "%d", options
.port
);
677 cp
= tilde_expand_filename(options
.control_path
,
679 xfree(options
.control_path
);
680 options
.control_path
= percent_expand(cp
, "p", buf
, "h", host
,
681 "r", options
.user
, "l", thishost
, (char *)NULL
);
684 if (mux_command
!= 0 && options
.control_path
== NULL
)
685 fatal("No ControlPath specified for \"-O\" command");
686 if (options
.control_path
!= NULL
)
687 control_client(options
.control_path
);
689 timeout_ms
= options
.connection_timeout
* 1000;
691 /* Open a connection to the remote host. */
692 if (ssh_connect(host
, &hostaddr
, options
.port
,
693 options
.address_family
, options
.connection_attempts
, &timeout_ms
,
694 options
.tcp_keep_alive
,
696 options
.use_privileged_port
,
698 original_effective_uid
== 0 && options
.use_privileged_port
,
700 options
.proxy_command
) != 0)
704 debug3("timeout: %d ms remain after connect", timeout_ms
);
707 * If we successfully made the connection, load the host private key
708 * in case we will need it later for combined rsa-rhosts
709 * authentication. This must be done before releasing extra
710 * privileges, because the file is only readable by root.
711 * If we cannot access the private keys, load the public keys
712 * instead and try to execute the ssh-keysign helper instead.
714 sensitive_data
.nkeys
= 0;
715 sensitive_data
.keys
= NULL
;
716 sensitive_data
.external_keysign
= 0;
717 if (options
.rhosts_rsa_authentication
||
718 options
.hostbased_authentication
) {
719 sensitive_data
.nkeys
= 3;
720 sensitive_data
.keys
= xcalloc(sensitive_data
.nkeys
,
724 sensitive_data
.keys
[0] = key_load_private_type(KEY_RSA1
,
725 _PATH_HOST_KEY_FILE
, "", NULL
, NULL
);
726 sensitive_data
.keys
[1] = key_load_private_type(KEY_DSA
,
727 _PATH_HOST_DSA_KEY_FILE
, "", NULL
, NULL
);
728 sensitive_data
.keys
[2] = key_load_private_type(KEY_RSA
,
729 _PATH_HOST_RSA_KEY_FILE
, "", NULL
, NULL
);
732 if (options
.hostbased_authentication
== 1 &&
733 sensitive_data
.keys
[0] == NULL
&&
734 sensitive_data
.keys
[1] == NULL
&&
735 sensitive_data
.keys
[2] == NULL
) {
736 sensitive_data
.keys
[1] = key_load_public(
737 _PATH_HOST_DSA_KEY_FILE
, NULL
);
738 sensitive_data
.keys
[2] = key_load_public(
739 _PATH_HOST_RSA_KEY_FILE
, NULL
);
740 sensitive_data
.external_keysign
= 1;
744 * Get rid of any extra privileges that we may have. We will no
745 * longer need them. Also, extra privileges could make it very hard
746 * to read identity files and other non-world-readable files from the
747 * user's home directory if it happens to be on a NFS volume where
748 * root is mapped to nobody.
750 if (original_effective_uid
== 0) {
752 permanently_set_uid(pw
);
756 * Now that we are back to our own permissions, create ~/.ssh
757 * directory if it doesn't already exist.
759 snprintf(buf
, sizeof buf
, "%.100s%s%.100s", pw
->pw_dir
, strcmp(pw
->pw_dir
, "/") ? "/" : "", _PATH_SSH_USER_DIR
);
760 if (stat(buf
, &st
) < 0)
761 if (mkdir(buf
, 0700) < 0)
762 error("Could not create directory '%.200s'.", buf
);
764 /* load options.identity_files */
765 load_public_identity_files();
767 /* Expand ~ in known host file names. */
769 options
.system_hostfile
=
770 tilde_expand_filename(options
.system_hostfile
, original_real_uid
);
771 options
.user_hostfile
=
772 tilde_expand_filename(options
.user_hostfile
, original_real_uid
);
773 options
.system_hostfile2
=
774 tilde_expand_filename(options
.system_hostfile2
, original_real_uid
);
775 options
.user_hostfile2
=
776 tilde_expand_filename(options
.user_hostfile2
, original_real_uid
);
778 signal(SIGPIPE
, SIG_IGN
); /* ignore SIGPIPE early */
780 /* Log into the remote system. This never returns if the login fails. */
781 ssh_login(&sensitive_data
, host
, (struct sockaddr
*)&hostaddr
,
784 /* We no longer need the private host keys. Clear them now. */
785 if (sensitive_data
.nkeys
!= 0) {
786 for (i
= 0; i
< sensitive_data
.nkeys
; i
++) {
787 if (sensitive_data
.keys
[i
] != NULL
) {
788 /* Destroys contents safely */
789 debug3("clear hostkey %d", i
);
790 key_free(sensitive_data
.keys
[i
]);
791 sensitive_data
.keys
[i
] = NULL
;
794 xfree(sensitive_data
.keys
);
796 for (i
= 0; i
< options
.num_identity_files
; i
++) {
797 if (options
.identity_files
[i
]) {
798 xfree(options
.identity_files
[i
]);
799 options
.identity_files
[i
] = NULL
;
801 if (options
.identity_keys
[i
]) {
802 key_free(options
.identity_keys
[i
]);
803 options
.identity_keys
[i
] = NULL
;
807 exit_status
= compat20
? ssh_session2() : ssh_session();
810 if (options
.control_path
!= NULL
&& control_fd
!= -1)
811 unlink(options
.control_path
);
814 * Send SIGHUP to proxy command if used. We don't wait() in
815 * case it hangs and instead rely on init to reap the child
817 if (proxy_command_pid
> 1)
818 kill(proxy_command_pid
, SIGHUP
);
824 ssh_init_forwarding(void)
829 /* Initiate local TCP/IP port forwardings. */
830 for (i
= 0; i
< options
.num_local_forwards
; i
++) {
831 debug("Local connections to %.200s:%d forwarded to remote "
833 (options
.local_forwards
[i
].listen_host
== NULL
) ?
834 (options
.gateway_ports
? "*" : "LOCALHOST") :
835 options
.local_forwards
[i
].listen_host
,
836 options
.local_forwards
[i
].listen_port
,
837 options
.local_forwards
[i
].connect_host
,
838 options
.local_forwards
[i
].connect_port
);
839 success
+= channel_setup_local_fwd_listener(
840 options
.local_forwards
[i
].listen_host
,
841 options
.local_forwards
[i
].listen_port
,
842 options
.local_forwards
[i
].connect_host
,
843 options
.local_forwards
[i
].connect_port
,
844 options
.gateway_ports
);
846 if (i
> 0 && success
!= i
&& options
.exit_on_forward_failure
)
847 fatal("Could not request local forwarding.");
848 if (i
> 0 && success
== 0)
849 error("Could not request local forwarding.");
851 /* Initiate remote TCP/IP port forwardings. */
852 for (i
= 0; i
< options
.num_remote_forwards
; i
++) {
853 debug("Remote connections from %.200s:%d forwarded to "
854 "local address %.200s:%d",
855 (options
.remote_forwards
[i
].listen_host
== NULL
) ?
856 "LOCALHOST" : options
.remote_forwards
[i
].listen_host
,
857 options
.remote_forwards
[i
].listen_port
,
858 options
.remote_forwards
[i
].connect_host
,
859 options
.remote_forwards
[i
].connect_port
);
860 if (channel_request_remote_forwarding(
861 options
.remote_forwards
[i
].listen_host
,
862 options
.remote_forwards
[i
].listen_port
,
863 options
.remote_forwards
[i
].connect_host
,
864 options
.remote_forwards
[i
].connect_port
) < 0) {
865 if (options
.exit_on_forward_failure
)
866 fatal("Could not request remote forwarding.");
868 logit("Warning: Could not request remote "
873 /* Initiate tunnel forwarding. */
874 if (options
.tun_open
!= SSH_TUNMODE_NO
) {
875 if (client_request_tun_fwd(options
.tun_open
,
876 options
.tun_local
, options
.tun_remote
) == -1) {
877 if (options
.exit_on_forward_failure
)
878 fatal("Could not request tunnel forwarding.");
880 error("Could not request tunnel forwarding.");
886 check_agent_present(void)
888 if (options
.forward_agent
) {
889 /* Clear agent forwarding if we don't have an agent. */
890 if (!ssh_agent_present())
891 options
.forward_agent
= 0;
905 /* Enable compression if requested. */
906 if (options
.compression
) {
907 debug("Requesting compression at level %d.", options
.compression_level
);
909 if (options
.compression_level
< 1 || options
.compression_level
> 9)
910 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
912 /* Send the request. */
913 packet_start(SSH_CMSG_REQUEST_COMPRESSION
);
914 packet_put_int(options
.compression_level
);
917 type
= packet_read();
918 if (type
== SSH_SMSG_SUCCESS
)
919 packet_start_compression(options
.compression_level
);
920 else if (type
== SSH_SMSG_FAILURE
)
921 logit("Warning: Remote host refused compression.");
923 packet_disconnect("Protocol error waiting for compression response.");
925 /* Allocate a pseudo tty if appropriate. */
927 debug("Requesting pty.");
929 /* Start the packet. */
930 packet_start(SSH_CMSG_REQUEST_PTY
);
932 /* Store TERM in the packet. There is no limit on the
933 length of the string. */
937 packet_put_cstring(cp
);
939 /* Store window size in the packet. */
940 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) < 0)
941 memset(&ws
, 0, sizeof(ws
));
942 packet_put_int((u_int
)ws
.ws_row
);
943 packet_put_int((u_int
)ws
.ws_col
);
944 packet_put_int((u_int
)ws
.ws_xpixel
);
945 packet_put_int((u_int
)ws
.ws_ypixel
);
947 /* Store tty modes in the packet. */
948 tty_make_modes(fileno(stdin
), NULL
);
950 /* Send the packet, and wait for it to leave. */
954 /* Read response from the server. */
955 type
= packet_read();
956 if (type
== SSH_SMSG_SUCCESS
) {
959 } else if (type
== SSH_SMSG_FAILURE
)
960 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
962 packet_disconnect("Protocol error waiting for pty request response.");
964 /* Request X11 forwarding if enabled and DISPLAY is set. */
965 display
= getenv("DISPLAY");
966 if (options
.forward_x11
&& display
!= NULL
) {
968 /* Get reasonable local authentication information. */
969 client_x11_get_proto(display
, options
.xauth_location
,
970 options
.forward_x11_trusted
, &proto
, &data
);
971 /* Request forwarding with authentication spoofing. */
972 debug("Requesting X11 forwarding with authentication spoofing.");
973 x11_request_forwarding_with_spoofing(0, display
, proto
, data
);
975 /* Read response from the server. */
976 type
= packet_read();
977 if (type
== SSH_SMSG_SUCCESS
) {
979 } else if (type
== SSH_SMSG_FAILURE
) {
980 logit("Warning: Remote host denied X11 forwarding.");
982 packet_disconnect("Protocol error waiting for X11 forwarding");
985 /* Tell the packet module whether this is an interactive session. */
986 packet_set_interactive(interactive
);
988 /* Request authentication agent forwarding if appropriate. */
989 check_agent_present();
991 if (options
.forward_agent
) {
992 debug("Requesting authentication agent forwarding.");
993 auth_request_forwarding();
995 /* Read response from the server. */
996 type
= packet_read();
998 if (type
!= SSH_SMSG_SUCCESS
)
999 logit("Warning: Remote host denied authentication agent forwarding.");
1002 /* Initiate port forwardings. */
1003 ssh_init_forwarding();
1005 /* Execute a local command */
1006 if (options
.local_command
!= NULL
&&
1007 options
.permit_local_command
)
1008 ssh_local_cmd(options
.local_command
);
1010 /* If requested, let ssh continue in the background. */
1011 if (fork_after_authentication_flag
)
1012 if (daemon(1, 1) < 0)
1013 fatal("daemon() failed: %.200s", strerror(errno
));
1016 * If a command was specified on the command line, execute the
1017 * command now. Otherwise request the server to start a shell.
1019 if (buffer_len(&command
) > 0) {
1020 int len
= buffer_len(&command
);
1023 debug("Sending command: %.*s", len
, (u_char
*)buffer_ptr(&command
));
1024 packet_start(SSH_CMSG_EXEC_CMD
);
1025 packet_put_string(buffer_ptr(&command
), buffer_len(&command
));
1027 packet_write_wait();
1029 debug("Requesting shell.");
1030 packet_start(SSH_CMSG_EXEC_SHELL
);
1032 packet_write_wait();
1035 /* Enter the interactive session. */
1036 return client_loop(have_tty
, tty_flag
?
1037 options
.escape_char
: SSH_ESCAPECHAR_NONE
, 0);
1041 ssh_subsystem_reply(int type
, u_int32_t seq
, void *ctxt
)
1045 id
= packet_get_int();
1046 len
= buffer_len(&command
);
1050 if (type
== SSH2_MSG_CHANNEL_FAILURE
)
1051 fatal("Request for subsystem '%.*s' failed on channel %d",
1052 len
, (u_char
*)buffer_ptr(&command
), id
);
1056 client_global_request_reply_fwd(int type
, u_int32_t seq
, void *ctxt
)
1060 i
= client_global_request_id
++;
1061 if (i
>= options
.num_remote_forwards
)
1063 debug("remote forward %s for: listen %d, connect %s:%d",
1064 type
== SSH2_MSG_REQUEST_SUCCESS
? "success" : "failure",
1065 options
.remote_forwards
[i
].listen_port
,
1066 options
.remote_forwards
[i
].connect_host
,
1067 options
.remote_forwards
[i
].connect_port
);
1068 if (type
== SSH2_MSG_REQUEST_FAILURE
) {
1069 if (options
.exit_on_forward_failure
)
1070 fatal("Error: remote port forwarding failed for "
1072 options
.remote_forwards
[i
].listen_port
);
1074 logit("Warning: remote port forwarding failed for "
1076 options
.remote_forwards
[i
].listen_port
);
1081 ssh_control_listener(void)
1083 struct sockaddr_un addr
;
1087 if (options
.control_path
== NULL
||
1088 options
.control_master
== SSHCTL_MASTER_NO
)
1091 debug("setting up multiplex master socket");
1093 memset(&addr
, '\0', sizeof(addr
));
1094 addr
.sun_family
= AF_UNIX
;
1095 addr_len
= offsetof(struct sockaddr_un
, sun_path
) +
1096 strlen(options
.control_path
) + 1;
1098 if (strlcpy(addr
.sun_path
, options
.control_path
,
1099 sizeof(addr
.sun_path
)) >= sizeof(addr
.sun_path
))
1100 fatal("ControlPath too long");
1102 if ((control_fd
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
1103 fatal("%s socket(): %s", __func__
, strerror(errno
));
1105 old_umask
= umask(0177);
1106 if (bind(control_fd
, (struct sockaddr
*)&addr
, addr_len
) == -1) {
1108 if (errno
== EINVAL
|| errno
== EADDRINUSE
)
1109 fatal("ControlSocket %s already exists",
1110 options
.control_path
);
1112 fatal("%s bind(): %s", __func__
, strerror(errno
));
1116 if (listen(control_fd
, 64) == -1)
1117 fatal("%s listen(): %s", __func__
, strerror(errno
));
1119 set_nonblock(control_fd
);
1122 /* request pty/x11/agent/tcpfwd/shell for channel */
1124 ssh_session2_setup(int id
, void *arg
)
1126 extern char **environ
;
1127 const char *display
;
1128 int interactive
= tty_flag
;
1130 display
= getenv("DISPLAY");
1131 if (options
.forward_x11
&& display
!= NULL
) {
1133 /* Get reasonable local authentication information. */
1134 client_x11_get_proto(display
, options
.xauth_location
,
1135 options
.forward_x11_trusted
, &proto
, &data
);
1136 /* Request forwarding with authentication spoofing. */
1137 debug("Requesting X11 forwarding with authentication spoofing.");
1138 x11_request_forwarding_with_spoofing(id
, display
, proto
, data
);
1140 /* XXX wait for reply */
1143 check_agent_present();
1144 if (options
.forward_agent
) {
1145 debug("Requesting authentication agent forwarding.");
1146 channel_request_start(id
, "auth-agent-req@openssh.com", 0);
1150 client_session2_setup(id
, tty_flag
, subsystem_flag
, getenv("TERM"),
1151 NULL
, fileno(stdin
), &command
, environ
, &ssh_subsystem_reply
);
1153 packet_set_interactive(interactive
);
1156 /* open new channel for a session */
1158 ssh_session2_open(void)
1161 int window
, packetmax
, in
, out
, err
;
1163 if (stdin_null_flag
) {
1164 in
= open(_PATH_DEVNULL
, O_RDONLY
);
1166 in
= dup(STDIN_FILENO
);
1168 out
= dup(STDOUT_FILENO
);
1169 err
= dup(STDERR_FILENO
);
1171 if (in
< 0 || out
< 0 || err
< 0)
1172 fatal("dup() in/out/err failed");
1174 /* enable nonblocking unless tty */
1182 window
= CHAN_SES_WINDOW_DEFAULT
;
1183 packetmax
= CHAN_SES_PACKET_DEFAULT
;
1189 "session", SSH_CHANNEL_OPENING
, in
, out
, err
,
1190 window
, packetmax
, CHAN_EXTENDED_WRITE
,
1191 "client-session", /*nonblock*/0);
1193 debug3("ssh_session2_open: channel_new: %d", c
->self
);
1195 channel_send_open(c
->self
);
1197 channel_register_confirm(c
->self
, ssh_session2_setup
, NULL
);
1207 /* XXX should be pre-session */
1208 ssh_init_forwarding();
1210 if (!no_shell_flag
|| (datafellows
& SSH_BUG_DUMMYCHAN
))
1211 id
= ssh_session2_open();
1213 /* Execute a local command */
1214 if (options
.local_command
!= NULL
&&
1215 options
.permit_local_command
)
1216 ssh_local_cmd(options
.local_command
);
1218 /* Start listening for multiplex clients */
1219 ssh_control_listener();
1221 /* If requested, let ssh continue in the background. */
1222 if (fork_after_authentication_flag
)
1223 if (daemon(1, 1) < 0)
1224 fatal("daemon() failed: %.200s", strerror(errno
));
1226 return client_loop(tty_flag
, tty_flag
?
1227 options
.escape_char
: SSH_ESCAPECHAR_NONE
, id
);
1231 load_public_identity_files(void)
1233 char *filename
, *cp
, thishost
[NI_MAXHOST
];
1234 char *pwdir
= NULL
, *pwname
= NULL
;
1241 if (options
.smartcard_device
!= NULL
&&
1242 options
.num_identity_files
< SSH_MAX_IDENTITY_FILES
&&
1243 (keys
= sc_get_keys(options
.smartcard_device
, NULL
)) != NULL
) {
1245 for (i
= 0; keys
[i
] != NULL
; i
++) {
1247 memmove(&options
.identity_files
[1], &options
.identity_files
[0],
1248 sizeof(char *) * (SSH_MAX_IDENTITY_FILES
- 1));
1249 memmove(&options
.identity_keys
[1], &options
.identity_keys
[0],
1250 sizeof(Key
*) * (SSH_MAX_IDENTITY_FILES
- 1));
1251 options
.num_identity_files
++;
1252 options
.identity_keys
[0] = keys
[i
];
1253 options
.identity_files
[0] = sc_get_key_label(keys
[i
]);
1255 if (options
.num_identity_files
> SSH_MAX_IDENTITY_FILES
)
1256 options
.num_identity_files
= SSH_MAX_IDENTITY_FILES
;
1260 #endif /* SMARTCARD */
1261 if ((pw
= getpwuid(original_real_uid
)) == NULL
)
1262 fatal("load_public_identity_files: getpwuid failed");
1263 pwname
= xstrdup(pw
->pw_name
);
1264 pwdir
= xstrdup(pw
->pw_dir
);
1265 if (gethostname(thishost
, sizeof(thishost
)) == -1)
1266 fatal("load_public_identity_files: gethostname: %s",
1268 for (; i
< options
.num_identity_files
; i
++) {
1269 cp
= tilde_expand_filename(options
.identity_files
[i
],
1271 filename
= percent_expand(cp
, "d", pwdir
,
1272 "u", pwname
, "l", thishost
, "h", host
,
1273 "r", options
.user
, (char *)NULL
);
1275 public = key_load_public(filename
, NULL
);
1276 debug("identity file %s type %d", filename
,
1277 public ? public->type
: -1);
1278 xfree(options
.identity_files
[i
]);
1279 options
.identity_files
[i
] = filename
;
1280 options
.identity_keys
[i
] = public;
1282 bzero(pwname
, strlen(pwname
));
1284 bzero(pwdir
, strlen(pwdir
));
1289 control_client_sighandler(int signo
)
1291 control_client_terminate
= signo
;
1295 control_client_sigrelay(int signo
)
1297 int save_errno
= errno
;
1299 if (control_server_pid
> 1)
1300 kill(control_server_pid
, signo
);
1306 env_permitted(char *env
)
1309 char name
[1024], *cp
;
1311 if ((cp
= strchr(env
, '=')) == NULL
|| cp
== env
)
1313 ret
= snprintf(name
, sizeof(name
), "%.*s", (int)(cp
- env
), env
);
1314 if (ret
<= 0 || (size_t)ret
>= sizeof(name
))
1315 fatal("env_permitted: name '%.100s...' too long", env
);
1317 for (i
= 0; i
< options
.num_send_env
; i
++)
1318 if (match_pattern(name
, options
.send_env
[i
]))
1325 control_client(const char *path
)
1327 struct sockaddr_un addr
;
1328 int i
, r
, fd
, sock
, exitval
[2], num_env
, addr_len
;
1331 extern char **environ
;
1334 if (mux_command
== 0)
1335 mux_command
= SSHMUX_COMMAND_OPEN
;
1337 switch (options
.control_master
) {
1338 case SSHCTL_MASTER_AUTO
:
1339 case SSHCTL_MASTER_AUTO_ASK
:
1340 debug("auto-mux: Trying existing master");
1342 case SSHCTL_MASTER_NO
:
1348 memset(&addr
, '\0', sizeof(addr
));
1349 addr
.sun_family
= AF_UNIX
;
1350 addr_len
= offsetof(struct sockaddr_un
, sun_path
) +
1353 if (strlcpy(addr
.sun_path
, path
,
1354 sizeof(addr
.sun_path
)) >= sizeof(addr
.sun_path
))
1355 fatal("ControlPath too long");
1357 if ((sock
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
1358 fatal("%s socket(): %s", __func__
, strerror(errno
));
1360 if (connect(sock
, (struct sockaddr
*)&addr
, addr_len
) == -1) {
1361 if (mux_command
!= SSHMUX_COMMAND_OPEN
) {
1362 fatal("Control socket connect(%.100s): %s", path
,
1365 if (errno
== ENOENT
)
1366 debug("Control socket \"%.100s\" does not exist", path
);
1368 error("Control socket connect(%.100s): %s", path
,
1375 if (stdin_null_flag
) {
1376 if ((fd
= open(_PATH_DEVNULL
, O_RDONLY
)) == -1)
1377 fatal("open(/dev/null): %s", strerror(errno
));
1378 if (dup2(fd
, STDIN_FILENO
) == -1)
1379 fatal("dup2: %s", strerror(errno
));
1380 if (fd
> STDERR_FILENO
)
1384 term
= getenv("TERM");
1388 flags
|= SSHMUX_FLAG_TTY
;
1390 flags
|= SSHMUX_FLAG_SUBSYS
;
1391 if (options
.forward_x11
)
1392 flags
|= SSHMUX_FLAG_X11_FWD
;
1393 if (options
.forward_agent
)
1394 flags
|= SSHMUX_FLAG_AGENT_FWD
;
1396 signal(SIGPIPE
, SIG_IGN
);
1400 /* Send our command to server */
1401 buffer_put_int(&m
, mux_command
);
1402 buffer_put_int(&m
, flags
);
1403 if (ssh_msg_send(sock
, SSHMUX_VER
, &m
) == -1)
1404 fatal("%s: msg_send", __func__
);
1407 /* Get authorisation status and PID of controlee */
1408 if (ssh_msg_recv(sock
, &m
) == -1)
1409 fatal("%s: msg_recv", __func__
);
1410 if (buffer_get_char(&m
) != SSHMUX_VER
)
1411 fatal("%s: wrong version", __func__
);
1412 if (buffer_get_int(&m
) != 1)
1413 fatal("Connection to master denied");
1414 control_server_pid
= buffer_get_int(&m
);
1418 switch (mux_command
) {
1419 case SSHMUX_COMMAND_ALIVE_CHECK
:
1420 fprintf(stderr
, "Master running (pid=%d)\r\n",
1421 control_server_pid
);
1423 case SSHMUX_COMMAND_TERMINATE
:
1424 fprintf(stderr
, "Exit request sent.\r\n");
1426 case SSHMUX_COMMAND_OPEN
:
1427 /* continue below */
1430 fatal("silly mux_command %d", mux_command
);
1433 /* SSHMUX_COMMAND_OPEN */
1434 buffer_put_cstring(&m
, term
? term
: "");
1435 buffer_append(&command
, "\0", 1);
1436 buffer_put_cstring(&m
, buffer_ptr(&command
));
1438 if (options
.num_send_env
== 0 || environ
== NULL
) {
1439 buffer_put_int(&m
, 0);
1441 /* Pass environment */
1443 for (i
= 0; environ
[i
] != NULL
; i
++)
1444 if (env_permitted(environ
[i
]))
1445 num_env
++; /* Count */
1447 buffer_put_int(&m
, num_env
);
1449 for (i
= 0; environ
[i
] != NULL
&& num_env
>= 0; i
++)
1450 if (env_permitted(environ
[i
])) {
1452 buffer_put_cstring(&m
, environ
[i
]);
1456 if (ssh_msg_send(sock
, SSHMUX_VER
, &m
) == -1)
1457 fatal("%s: msg_send", __func__
);
1459 if (mm_send_fd(sock
, STDIN_FILENO
) == -1 ||
1460 mm_send_fd(sock
, STDOUT_FILENO
) == -1 ||
1461 mm_send_fd(sock
, STDERR_FILENO
) == -1)
1462 fatal("%s: send fds failed", __func__
);
1464 /* Wait for reply, so master has a chance to gather ttymodes */
1466 if (ssh_msg_recv(sock
, &m
) == -1)
1467 fatal("%s: msg_recv", __func__
);
1468 if (buffer_get_char(&m
) != SSHMUX_VER
)
1469 fatal("%s: wrong version", __func__
);
1472 signal(SIGHUP
, control_client_sighandler
);
1473 signal(SIGINT
, control_client_sighandler
);
1474 signal(SIGTERM
, control_client_sighandler
);
1475 signal(SIGWINCH
, control_client_sigrelay
);
1481 * Stick around until the controlee closes the client_fd.
1482 * Before it does, it is expected to write this process' exit
1483 * value (one int). This process must read the value and wait for
1484 * the closure of the client_fd; if this one closes early, the
1485 * multiplex master will terminate early too (possibly losing data).
1488 for (i
= 0; !control_client_terminate
&& i
< (int)sizeof(exitval
);) {
1489 r
= read(sock
, (char *)exitval
+ i
, sizeof(exitval
) - i
);
1491 debug2("Received EOF from master");
1497 fatal("%s: read %s", __func__
, strerror(errno
));
1504 if (i
> (int)sizeof(int))
1505 fatal("%s: master returned too much data (%d > %lu)",
1506 __func__
, i
, sizeof(int));
1507 if (control_client_terminate
) {
1508 debug2("Exiting on signal %d", control_client_terminate
);
1510 } else if (i
< (int)sizeof(int)) {
1511 debug2("Control master terminated unexpectedly");
1514 debug2("Received exit status from master %d", exitval
[0]);
1516 if (tty_flag
&& options
.log_level
!= SYSLOG_LEVEL_QUIET
)
1517 fprintf(stderr
, "Shared connection to %s closed.\r\n", host
);