1 /* $OpenBSD: ssh.c,v 1.288 2006/07/17 01:31:10 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>
57 #if defined(HAVE_NETDB_H)
68 #include <openssl/evp.h>
69 #include <openssl/err.h>
84 #include "pathnames.h"
86 #include "clientloop.h"
89 #include "sshconnect.h"
96 #include "monitor_fdpass.h"
104 extern char *__progname
;
106 /* Flag indicating whether debug mode is on. This can be set on the command line. */
109 /* Flag indicating whether a tty should be allocated */
112 int force_tty_flag
= 0;
114 /* don't exec a shell */
115 int no_shell_flag
= 0;
118 * Flag indicating that nothing should be read from stdin. This can be set
119 * on the command line.
121 int stdin_null_flag
= 0;
124 * Flag indicating that ssh should fork after authentication. This is useful
125 * so that the passphrase can be entered manually, and then ssh goes to the
128 int fork_after_authentication_flag
= 0;
131 * General data structure for command line options and options configurable
132 * in configuration files. See readconf.h.
136 /* optional user configfile */
140 * Name of the host we are connecting to. This is the name given on the
141 * command line, or the HostName specified for the user-supplied name in a
142 * configuration file.
146 /* socket address the host resolves to */
147 struct sockaddr_storage hostaddr
;
149 /* Private host keys. */
150 Sensitive sensitive_data
;
152 /* Original real UID. */
153 uid_t original_real_uid
;
154 uid_t original_effective_uid
;
156 /* command to be executed */
159 /* Should we execute a command or invoke a subsystem? */
160 int subsystem_flag
= 0;
162 /* # of replies received for global requests */
163 static int client_global_request_id
= 0;
165 /* pid of proxycommand child process */
166 pid_t proxy_command_pid
= 0;
168 /* fd to control socket */
171 /* Multiplexing control command */
172 static u_int mux_command
= 0;
174 /* Only used in control client mode */
175 volatile sig_atomic_t control_client_terminate
= 0;
176 u_int control_server_pid
= 0;
178 /* Prints a help message to the user. This function never returns. */
184 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
185 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
186 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
187 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
188 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
189 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
194 static int ssh_session(void);
195 static int ssh_session2(void);
196 static void load_public_identity_files(void);
197 static void control_client(const char *path
);
200 * Main program for the ssh client.
203 main(int ac
, char **av
)
205 int i
, opt
, exit_status
;
206 char *p
, *cp
, *line
, buf
[256];
210 extern int optind
, optreset
;
215 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
218 __progname
= ssh_get_progname(av
[0]);
222 * Save the original real uid. It will be needed later (uid-swapping
223 * may clobber the real uid).
225 original_real_uid
= getuid();
226 original_effective_uid
= geteuid();
229 * Use uid-swapping to give up root privileges for the duration of
230 * option processing. We will re-instantiate the rights when we are
231 * ready to create the privileged port, and will permanently drop
232 * them when the port has been created (actually, when the connection
233 * has been made, as we may need to create the port several times).
237 #ifdef HAVE_SETRLIMIT
238 /* If we are installed setuid root be careful to not drop core. */
239 if (original_real_uid
!= original_effective_uid
) {
241 rlim
.rlim_cur
= rlim
.rlim_max
= 0;
242 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
243 fatal("setrlimit failed: %.100s", strerror(errno
));
247 pw
= getpwuid(original_real_uid
);
249 logit("You don't exist, go away!");
252 /* Take a copy of the returned structure. */
256 * Set our umask to something reasonable, as some files are created
257 * with the default umask. This will make them world-readable but
258 * writable only by the owner, which is ok for all files for which we
259 * don't set the modes explicitly.
263 /* Initialize option structure to indicate that no values have been set. */
264 initialize_options(&options
);
266 /* Parse command-line arguments. */
270 while ((opt
= getopt(ac
, av
,
271 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
274 options
.protocol
= SSH_PROTO_1
;
277 options
.protocol
= SSH_PROTO_2
;
280 options
.address_family
= AF_INET
;
283 options
.address_family
= AF_INET6
;
289 fork_after_authentication_flag
= 1;
293 options
.forward_x11
= 0;
296 options
.forward_x11
= 1;
299 options
.forward_x11
= 1;
300 options
.forward_x11_trusted
= 1;
303 options
.gateway_ports
= 1;
306 if (strcmp(optarg
, "check") == 0)
307 mux_command
= SSHMUX_COMMAND_ALIVE_CHECK
;
308 else if (strcmp(optarg
, "exit") == 0)
309 mux_command
= SSHMUX_COMMAND_TERMINATE
;
311 fatal("Invalid multiplex command.");
313 case 'P': /* deprecated */
314 options
.use_privileged_port
= 0;
317 options
.forward_agent
= 0;
320 options
.forward_agent
= 1;
323 options
.gss_deleg_creds
= 0;
326 if (stat(optarg
, &st
) < 0) {
327 fprintf(stderr
, "Warning: Identity file %s "
328 "not accessible: %s.\n", optarg
,
332 if (options
.num_identity_files
>=
333 SSH_MAX_IDENTITY_FILES
)
334 fatal("Too many identity files specified "
335 "(max %d)", SSH_MAX_IDENTITY_FILES
);
336 options
.identity_files
[options
.num_identity_files
++] =
341 options
.smartcard_device
= xstrdup(optarg
);
343 fprintf(stderr
, "no support for smartcards.\n");
352 if (debug_flag
== 0) {
354 options
.log_level
= SYSLOG_LEVEL_DEBUG1
;
356 if (options
.log_level
< SYSLOG_LEVEL_DEBUG3
)
362 fprintf(stderr
, "%s, %s\n",
363 SSH_RELEASE
, SSLeay_version(SSLEAY_VERSION
));
368 if (options
.tun_open
== -1)
369 options
.tun_open
= SSH_TUNMODE_DEFAULT
;
370 options
.tun_local
= a2tun(optarg
, &options
.tun_remote
);
371 if (options
.tun_local
== SSH_TUNID_ERR
) {
372 fprintf(stderr
, "Bad tun device '%s'\n", optarg
);
377 options
.log_level
= SYSLOG_LEVEL_QUIET
;
380 if (optarg
[0] == '^' && optarg
[2] == 0 &&
381 (u_char
) optarg
[1] >= 64 &&
382 (u_char
) optarg
[1] < 128)
383 options
.escape_char
= (u_char
) optarg
[1] & 31;
384 else if (strlen(optarg
) == 1)
385 options
.escape_char
= (u_char
) optarg
[0];
386 else if (strcmp(optarg
, "none") == 0)
387 options
.escape_char
= SSH_ESCAPECHAR_NONE
;
389 fprintf(stderr
, "Bad escape character '%s'.\n",
395 if (ciphers_valid(optarg
)) {
397 options
.ciphers
= xstrdup(optarg
);
398 options
.cipher
= SSH_CIPHER_INVALID
;
401 options
.cipher
= cipher_number(optarg
);
402 if (options
.cipher
== -1) {
404 "Unknown cipher type '%s'\n",
408 if (options
.cipher
== SSH_CIPHER_3DES
)
409 options
.ciphers
= "3des-cbc";
410 else if (options
.cipher
== SSH_CIPHER_BLOWFISH
)
411 options
.ciphers
= "blowfish-cbc";
413 options
.ciphers
= (char *)-1;
417 if (mac_valid(optarg
))
418 options
.macs
= xstrdup(optarg
);
420 fprintf(stderr
, "Unknown mac type '%s'\n",
426 if (options
.control_master
== SSHCTL_MASTER_YES
)
427 options
.control_master
= SSHCTL_MASTER_ASK
;
429 options
.control_master
= SSHCTL_MASTER_YES
;
432 options
.port
= a2port(optarg
);
433 if (options
.port
== 0) {
434 fprintf(stderr
, "Bad port '%s'\n", optarg
);
439 options
.user
= optarg
;
443 if (parse_forward(&fwd
, optarg
))
444 add_local_forward(&options
, &fwd
);
447 "Bad local forwarding specification '%s'\n",
454 if (parse_forward(&fwd
, optarg
)) {
455 add_remote_forward(&options
, &fwd
);
458 "Bad remote forwarding specification "
465 cp
= p
= xstrdup(optarg
);
466 memset(&fwd
, '\0', sizeof(fwd
));
467 fwd
.connect_host
= "socks";
468 if ((fwd
.listen_host
= hpdelim(&cp
)) == NULL
) {
469 fprintf(stderr
, "Bad dynamic forwarding "
470 "specification '%.100s'\n", optarg
);
474 fwd
.listen_port
= a2port(cp
);
475 fwd
.listen_host
= cleanhostname(fwd
.listen_host
);
477 fwd
.listen_port
= a2port(fwd
.listen_host
);
478 fwd
.listen_host
= NULL
;
481 if (fwd
.listen_port
== 0) {
482 fprintf(stderr
, "Bad dynamic port '%s'\n",
486 add_local_forward(&options
, &fwd
);
491 options
.compression
= 1;
502 line
= xstrdup(optarg
);
503 if (process_config_line(&options
, host
? host
: "",
504 line
, "command-line", 0, &dummy
) != 0)
512 if (options
.control_path
!= NULL
)
513 free(options
.control_path
);
514 options
.control_path
= xstrdup(optarg
);
517 options
.bind_address
= optarg
;
530 if (ac
> 0 && !host
&& **av
!= '-') {
531 if (strrchr(*av
, '@')) {
533 cp
= strrchr(p
, '@');
534 if (cp
== NULL
|| cp
== p
)
542 optind
= optreset
= 1;
548 /* Check that we got a host name. */
552 SSLeay_add_all_algorithms();
553 ERR_load_crypto_strings();
555 /* Initialize the command to execute on remote host. */
556 buffer_init(&command
);
559 * Save the command to execute on the remote host in a buffer. There
560 * is no limit on the length of the command, except by the maximum
561 * packet size. Also sets the tty flag if there is no command.
564 /* No command specified - execute shell on a tty. */
566 if (subsystem_flag
) {
568 "You must specify a subsystem to invoke.\n");
572 /* A command has been specified. Store it into the buffer. */
573 for (i
= 0; i
< ac
; i
++) {
575 buffer_append(&command
, " ", 1);
576 buffer_append(&command
, av
[i
], strlen(av
[i
]));
580 /* Cannot fork to background if no command. */
581 if (fork_after_authentication_flag
&& buffer_len(&command
) == 0 && !no_shell_flag
)
582 fatal("Cannot fork into background without a command to execute.");
584 /* Allocate a tty by default if no command specified. */
585 if (buffer_len(&command
) == 0)
591 /* Do not allocate a tty if stdin is not a tty. */
592 if ((!isatty(fileno(stdin
)) || stdin_null_flag
) && !force_tty_flag
) {
594 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
599 * Initialize "log" output. Since we are the client all output
600 * actually goes to stderr.
602 log_init(av
[0], options
.log_level
== -1 ? SYSLOG_LEVEL_INFO
: options
.log_level
,
603 SYSLOG_FACILITY_USER
, 1);
606 * Read per-user configuration file. Ignore the system wide config
607 * file if the user specifies a config file on the command line.
609 if (config
!= NULL
) {
610 if (!read_config_file(config
, host
, &options
, 0))
611 fatal("Can't open user config file %.100s: "
612 "%.100s", config
, strerror(errno
));
614 snprintf(buf
, sizeof buf
, "%.100s/%.100s", pw
->pw_dir
,
615 _PATH_SSH_USER_CONFFILE
);
616 (void)read_config_file(buf
, host
, &options
, 1);
618 /* Read systemwide configuration file after use config. */
619 (void)read_config_file(_PATH_HOST_CONFIG_FILE
, host
,
623 /* Fill configuration defaults. */
624 fill_default_options(&options
);
626 channel_set_af(options
.address_family
);
629 log_init(av
[0], options
.log_level
, SYSLOG_FACILITY_USER
, 1);
633 if (options
.user
== NULL
)
634 options
.user
= xstrdup(pw
->pw_name
);
636 if (options
.hostname
!= NULL
)
637 host
= options
.hostname
;
639 /* force lowercase for hostkey matching */
640 if (options
.host_key_alias
!= NULL
) {
641 for (p
= options
.host_key_alias
; *p
; p
++)
643 *p
= (char)tolower(*p
);
646 /* Get default port if port has not been set. */
647 if (options
.port
== 0) {
648 sp
= getservbyname(SSH_SERVICE_NAME
, "tcp");
649 options
.port
= sp
? ntohs(sp
->s_port
) : SSH_DEFAULT_PORT
;
652 if (options
.proxy_command
!= NULL
&&
653 strcmp(options
.proxy_command
, "none") == 0)
654 options
.proxy_command
= NULL
;
655 if (options
.control_path
!= NULL
&&
656 strcmp(options
.control_path
, "none") == 0)
657 options
.control_path
= NULL
;
659 if (options
.control_path
!= NULL
) {
660 char thishost
[NI_MAXHOST
];
662 if (gethostname(thishost
, sizeof(thishost
)) == -1)
663 fatal("gethostname: %s", strerror(errno
));
664 snprintf(buf
, sizeof(buf
), "%d", options
.port
);
665 cp
= tilde_expand_filename(options
.control_path
,
667 options
.control_path
= percent_expand(cp
, "p", buf
, "h", host
,
668 "r", options
.user
, "l", thishost
, (char *)NULL
);
671 if (mux_command
!= 0 && options
.control_path
== NULL
)
672 fatal("No ControlPath specified for \"-O\" command");
673 if (options
.control_path
!= NULL
)
674 control_client(options
.control_path
);
676 /* Open a connection to the remote host. */
677 if (ssh_connect(host
, &hostaddr
, options
.port
,
678 options
.address_family
, options
.connection_attempts
,
680 options
.use_privileged_port
,
682 original_effective_uid
== 0 && options
.use_privileged_port
,
684 options
.proxy_command
) != 0)
688 * If we successfully made the connection, load the host private key
689 * in case we will need it later for combined rsa-rhosts
690 * authentication. This must be done before releasing extra
691 * privileges, because the file is only readable by root.
692 * If we cannot access the private keys, load the public keys
693 * instead and try to execute the ssh-keysign helper instead.
695 sensitive_data
.nkeys
= 0;
696 sensitive_data
.keys
= NULL
;
697 sensitive_data
.external_keysign
= 0;
698 if (options
.rhosts_rsa_authentication
||
699 options
.hostbased_authentication
) {
700 sensitive_data
.nkeys
= 3;
701 sensitive_data
.keys
= xcalloc(sensitive_data
.nkeys
,
705 sensitive_data
.keys
[0] = key_load_private_type(KEY_RSA1
,
706 _PATH_HOST_KEY_FILE
, "", NULL
, NULL
);
707 sensitive_data
.keys
[1] = key_load_private_type(KEY_DSA
,
708 _PATH_HOST_DSA_KEY_FILE
, "", NULL
, NULL
);
709 sensitive_data
.keys
[2] = key_load_private_type(KEY_RSA
,
710 _PATH_HOST_RSA_KEY_FILE
, "", NULL
, NULL
);
713 if (options
.hostbased_authentication
== 1 &&
714 sensitive_data
.keys
[0] == NULL
&&
715 sensitive_data
.keys
[1] == NULL
&&
716 sensitive_data
.keys
[2] == NULL
) {
717 sensitive_data
.keys
[1] = key_load_public(
718 _PATH_HOST_DSA_KEY_FILE
, NULL
);
719 sensitive_data
.keys
[2] = key_load_public(
720 _PATH_HOST_RSA_KEY_FILE
, NULL
);
721 sensitive_data
.external_keysign
= 1;
725 * Get rid of any extra privileges that we may have. We will no
726 * longer need them. Also, extra privileges could make it very hard
727 * to read identity files and other non-world-readable files from the
728 * user's home directory if it happens to be on a NFS volume where
729 * root is mapped to nobody.
731 if (original_effective_uid
== 0) {
733 permanently_set_uid(pw
);
737 * Now that we are back to our own permissions, create ~/.ssh
738 * directory if it doesn't already exist.
740 snprintf(buf
, sizeof buf
, "%.100s%s%.100s", pw
->pw_dir
, strcmp(pw
->pw_dir
, "/") ? "/" : "", _PATH_SSH_USER_DIR
);
741 if (stat(buf
, &st
) < 0)
742 if (mkdir(buf
, 0700) < 0)
743 error("Could not create directory '%.200s'.", buf
);
745 /* load options.identity_files */
746 load_public_identity_files();
748 /* Expand ~ in known host file names. */
750 options
.system_hostfile
=
751 tilde_expand_filename(options
.system_hostfile
, original_real_uid
);
752 options
.user_hostfile
=
753 tilde_expand_filename(options
.user_hostfile
, original_real_uid
);
754 options
.system_hostfile2
=
755 tilde_expand_filename(options
.system_hostfile2
, original_real_uid
);
756 options
.user_hostfile2
=
757 tilde_expand_filename(options
.user_hostfile2
, original_real_uid
);
759 signal(SIGPIPE
, SIG_IGN
); /* ignore SIGPIPE early */
761 /* Log into the remote system. This never returns if the login fails. */
762 ssh_login(&sensitive_data
, host
, (struct sockaddr
*)&hostaddr
, pw
);
764 /* We no longer need the private host keys. Clear them now. */
765 if (sensitive_data
.nkeys
!= 0) {
766 for (i
= 0; i
< sensitive_data
.nkeys
; i
++) {
767 if (sensitive_data
.keys
[i
] != NULL
) {
768 /* Destroys contents safely */
769 debug3("clear hostkey %d", i
);
770 key_free(sensitive_data
.keys
[i
]);
771 sensitive_data
.keys
[i
] = NULL
;
774 xfree(sensitive_data
.keys
);
776 for (i
= 0; i
< options
.num_identity_files
; i
++) {
777 if (options
.identity_files
[i
]) {
778 xfree(options
.identity_files
[i
]);
779 options
.identity_files
[i
] = NULL
;
781 if (options
.identity_keys
[i
]) {
782 key_free(options
.identity_keys
[i
]);
783 options
.identity_keys
[i
] = NULL
;
787 exit_status
= compat20
? ssh_session2() : ssh_session();
790 if (options
.control_path
!= NULL
&& control_fd
!= -1)
791 unlink(options
.control_path
);
794 * Send SIGHUP to proxy command if used. We don't wait() in
795 * case it hangs and instead rely on init to reap the child
797 if (proxy_command_pid
> 1)
798 kill(proxy_command_pid
, SIGHUP
);
804 ssh_init_forwarding(void)
809 /* Initiate local TCP/IP port forwardings. */
810 for (i
= 0; i
< options
.num_local_forwards
; i
++) {
811 debug("Local connections to %.200s:%d forwarded to remote "
813 (options
.local_forwards
[i
].listen_host
== NULL
) ?
814 (options
.gateway_ports
? "*" : "LOCALHOST") :
815 options
.local_forwards
[i
].listen_host
,
816 options
.local_forwards
[i
].listen_port
,
817 options
.local_forwards
[i
].connect_host
,
818 options
.local_forwards
[i
].connect_port
);
819 success
+= channel_setup_local_fwd_listener(
820 options
.local_forwards
[i
].listen_host
,
821 options
.local_forwards
[i
].listen_port
,
822 options
.local_forwards
[i
].connect_host
,
823 options
.local_forwards
[i
].connect_port
,
824 options
.gateway_ports
);
826 if (i
> 0 && success
!= i
&& options
.exit_on_forward_failure
)
827 fatal("Could not request local forwarding.");
828 if (i
> 0 && success
== 0)
829 error("Could not request local forwarding.");
831 /* Initiate remote TCP/IP port forwardings. */
832 for (i
= 0; i
< options
.num_remote_forwards
; i
++) {
833 debug("Remote connections from %.200s:%d forwarded to "
834 "local address %.200s:%d",
835 (options
.remote_forwards
[i
].listen_host
== NULL
) ?
836 "LOCALHOST" : options
.remote_forwards
[i
].listen_host
,
837 options
.remote_forwards
[i
].listen_port
,
838 options
.remote_forwards
[i
].connect_host
,
839 options
.remote_forwards
[i
].connect_port
);
840 if (channel_request_remote_forwarding(
841 options
.remote_forwards
[i
].listen_host
,
842 options
.remote_forwards
[i
].listen_port
,
843 options
.remote_forwards
[i
].connect_host
,
844 options
.remote_forwards
[i
].connect_port
) < 0) {
845 if (options
.exit_on_forward_failure
)
846 fatal("Could not request remote forwarding.");
848 logit("Warning: Could not request remote "
855 check_agent_present(void)
857 if (options
.forward_agent
) {
858 /* Clear agent forwarding if we don't have an agent. */
859 if (!ssh_agent_present())
860 options
.forward_agent
= 0;
874 /* Enable compression if requested. */
875 if (options
.compression
) {
876 debug("Requesting compression at level %d.", options
.compression_level
);
878 if (options
.compression_level
< 1 || options
.compression_level
> 9)
879 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
881 /* Send the request. */
882 packet_start(SSH_CMSG_REQUEST_COMPRESSION
);
883 packet_put_int(options
.compression_level
);
886 type
= packet_read();
887 if (type
== SSH_SMSG_SUCCESS
)
888 packet_start_compression(options
.compression_level
);
889 else if (type
== SSH_SMSG_FAILURE
)
890 logit("Warning: Remote host refused compression.");
892 packet_disconnect("Protocol error waiting for compression response.");
894 /* Allocate a pseudo tty if appropriate. */
896 debug("Requesting pty.");
898 /* Start the packet. */
899 packet_start(SSH_CMSG_REQUEST_PTY
);
901 /* Store TERM in the packet. There is no limit on the
902 length of the string. */
906 packet_put_cstring(cp
);
908 /* Store window size in the packet. */
909 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) < 0)
910 memset(&ws
, 0, sizeof(ws
));
911 packet_put_int((u_int
)ws
.ws_row
);
912 packet_put_int((u_int
)ws
.ws_col
);
913 packet_put_int((u_int
)ws
.ws_xpixel
);
914 packet_put_int((u_int
)ws
.ws_ypixel
);
916 /* Store tty modes in the packet. */
917 tty_make_modes(fileno(stdin
), NULL
);
919 /* Send the packet, and wait for it to leave. */
923 /* Read response from the server. */
924 type
= packet_read();
925 if (type
== SSH_SMSG_SUCCESS
) {
928 } else if (type
== SSH_SMSG_FAILURE
)
929 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
931 packet_disconnect("Protocol error waiting for pty request response.");
933 /* Request X11 forwarding if enabled and DISPLAY is set. */
934 display
= getenv("DISPLAY");
935 if (options
.forward_x11
&& display
!= NULL
) {
937 /* Get reasonable local authentication information. */
938 client_x11_get_proto(display
, options
.xauth_location
,
939 options
.forward_x11_trusted
, &proto
, &data
);
940 /* Request forwarding with authentication spoofing. */
941 debug("Requesting X11 forwarding with authentication spoofing.");
942 x11_request_forwarding_with_spoofing(0, display
, proto
, data
);
944 /* Read response from the server. */
945 type
= packet_read();
946 if (type
== SSH_SMSG_SUCCESS
) {
948 } else if (type
== SSH_SMSG_FAILURE
) {
949 logit("Warning: Remote host denied X11 forwarding.");
951 packet_disconnect("Protocol error waiting for X11 forwarding");
954 /* Tell the packet module whether this is an interactive session. */
955 packet_set_interactive(interactive
);
957 /* Request authentication agent forwarding if appropriate. */
958 check_agent_present();
960 if (options
.forward_agent
) {
961 debug("Requesting authentication agent forwarding.");
962 auth_request_forwarding();
964 /* Read response from the server. */
965 type
= packet_read();
967 if (type
!= SSH_SMSG_SUCCESS
)
968 logit("Warning: Remote host denied authentication agent forwarding.");
971 /* Initiate port forwardings. */
972 ssh_init_forwarding();
974 /* If requested, let ssh continue in the background. */
975 if (fork_after_authentication_flag
)
976 if (daemon(1, 1) < 0)
977 fatal("daemon() failed: %.200s", strerror(errno
));
980 * If a command was specified on the command line, execute the
981 * command now. Otherwise request the server to start a shell.
983 if (buffer_len(&command
) > 0) {
984 int len
= buffer_len(&command
);
987 debug("Sending command: %.*s", len
, (u_char
*)buffer_ptr(&command
));
988 packet_start(SSH_CMSG_EXEC_CMD
);
989 packet_put_string(buffer_ptr(&command
), buffer_len(&command
));
993 debug("Requesting shell.");
994 packet_start(SSH_CMSG_EXEC_SHELL
);
999 /* Enter the interactive session. */
1000 return client_loop(have_tty
, tty_flag
?
1001 options
.escape_char
: SSH_ESCAPECHAR_NONE
, 0);
1005 ssh_subsystem_reply(int type
, u_int32_t seq
, void *ctxt
)
1009 id
= packet_get_int();
1010 len
= buffer_len(&command
);
1014 if (type
== SSH2_MSG_CHANNEL_FAILURE
)
1015 fatal("Request for subsystem '%.*s' failed on channel %d",
1016 len
, (u_char
*)buffer_ptr(&command
), id
);
1020 client_global_request_reply_fwd(int type
, u_int32_t seq
, void *ctxt
)
1024 i
= client_global_request_id
++;
1025 if (i
>= options
.num_remote_forwards
)
1027 debug("remote forward %s for: listen %d, connect %s:%d",
1028 type
== SSH2_MSG_REQUEST_SUCCESS
? "success" : "failure",
1029 options
.remote_forwards
[i
].listen_port
,
1030 options
.remote_forwards
[i
].connect_host
,
1031 options
.remote_forwards
[i
].connect_port
);
1032 if (type
== SSH2_MSG_REQUEST_FAILURE
) {
1033 if (options
.exit_on_forward_failure
)
1034 fatal("Error: remote port forwarding failed for "
1036 options
.remote_forwards
[i
].listen_port
);
1038 logit("Warning: remote port forwarding failed for "
1040 options
.remote_forwards
[i
].listen_port
);
1045 ssh_control_listener(void)
1047 struct sockaddr_un addr
;
1051 if (options
.control_path
== NULL
||
1052 options
.control_master
== SSHCTL_MASTER_NO
)
1055 debug("setting up multiplex master socket");
1057 memset(&addr
, '\0', sizeof(addr
));
1058 addr
.sun_family
= AF_UNIX
;
1059 addr_len
= offsetof(struct sockaddr_un
, sun_path
) +
1060 strlen(options
.control_path
) + 1;
1062 if (strlcpy(addr
.sun_path
, options
.control_path
,
1063 sizeof(addr
.sun_path
)) >= sizeof(addr
.sun_path
))
1064 fatal("ControlPath too long");
1066 if ((control_fd
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
1067 fatal("%s socket(): %s", __func__
, strerror(errno
));
1069 old_umask
= umask(0177);
1070 if (bind(control_fd
, (struct sockaddr
*)&addr
, addr_len
) == -1) {
1072 if (errno
== EINVAL
|| errno
== EADDRINUSE
)
1073 fatal("ControlSocket %s already exists",
1074 options
.control_path
);
1076 fatal("%s bind(): %s", __func__
, strerror(errno
));
1080 if (listen(control_fd
, 64) == -1)
1081 fatal("%s listen(): %s", __func__
, strerror(errno
));
1083 set_nonblock(control_fd
);
1086 /* request pty/x11/agent/tcpfwd/shell for channel */
1088 ssh_session2_setup(int id
, void *arg
)
1090 extern char **environ
;
1091 const char *display
;
1092 int interactive
= tty_flag
;
1094 display
= getenv("DISPLAY");
1095 if (options
.forward_x11
&& display
!= NULL
) {
1097 /* Get reasonable local authentication information. */
1098 client_x11_get_proto(display
, options
.xauth_location
,
1099 options
.forward_x11_trusted
, &proto
, &data
);
1100 /* Request forwarding with authentication spoofing. */
1101 debug("Requesting X11 forwarding with authentication spoofing.");
1102 x11_request_forwarding_with_spoofing(id
, display
, proto
, data
);
1104 /* XXX wait for reply */
1107 check_agent_present();
1108 if (options
.forward_agent
) {
1109 debug("Requesting authentication agent forwarding.");
1110 channel_request_start(id
, "auth-agent-req@openssh.com", 0);
1114 if (options
.tun_open
!= SSH_TUNMODE_NO
) {
1118 debug("Requesting tun.");
1119 if ((fd
= tun_open(options
.tun_local
,
1120 options
.tun_open
)) >= 0) {
1121 c
= channel_new("tun", SSH_CHANNEL_OPENING
, fd
, fd
, -1,
1122 CHAN_TCP_WINDOW_DEFAULT
, CHAN_TCP_PACKET_DEFAULT
,
1125 #if defined(SSH_TUN_FILTER)
1126 if (options
.tun_open
== SSH_TUNMODE_POINTOPOINT
)
1127 channel_register_filter(c
->self
, sys_tun_infilter
,
1130 packet_start(SSH2_MSG_CHANNEL_OPEN
);
1131 packet_put_cstring("tun@openssh.com");
1132 packet_put_int(c
->self
);
1133 packet_put_int(c
->local_window_max
);
1134 packet_put_int(c
->local_maxpacket
);
1135 packet_put_int(options
.tun_open
);
1136 packet_put_int(options
.tun_remote
);
1141 client_session2_setup(id
, tty_flag
, subsystem_flag
, getenv("TERM"),
1142 NULL
, fileno(stdin
), &command
, environ
, &ssh_subsystem_reply
);
1144 packet_set_interactive(interactive
);
1147 /* open new channel for a session */
1149 ssh_session2_open(void)
1152 int window
, packetmax
, in
, out
, err
;
1154 if (stdin_null_flag
) {
1155 in
= open(_PATH_DEVNULL
, O_RDONLY
);
1157 in
= dup(STDIN_FILENO
);
1159 out
= dup(STDOUT_FILENO
);
1160 err
= dup(STDERR_FILENO
);
1162 if (in
< 0 || out
< 0 || err
< 0)
1163 fatal("dup() in/out/err failed");
1165 /* enable nonblocking unless tty */
1173 window
= CHAN_SES_WINDOW_DEFAULT
;
1174 packetmax
= CHAN_SES_PACKET_DEFAULT
;
1180 "session", SSH_CHANNEL_OPENING
, in
, out
, err
,
1181 window
, packetmax
, CHAN_EXTENDED_WRITE
,
1182 "client-session", /*nonblock*/0);
1184 debug3("ssh_session2_open: channel_new: %d", c
->self
);
1186 channel_send_open(c
->self
);
1188 channel_register_confirm(c
->self
, ssh_session2_setup
, NULL
);
1198 /* XXX should be pre-session */
1199 ssh_init_forwarding();
1200 ssh_control_listener();
1202 if (!no_shell_flag
|| (datafellows
& SSH_BUG_DUMMYCHAN
))
1203 id
= ssh_session2_open();
1205 /* Execute a local command */
1206 if (options
.local_command
!= NULL
&&
1207 options
.permit_local_command
)
1208 ssh_local_cmd(options
.local_command
);
1210 /* If requested, let ssh continue in the background. */
1211 if (fork_after_authentication_flag
)
1212 if (daemon(1, 1) < 0)
1213 fatal("daemon() failed: %.200s", strerror(errno
));
1215 return client_loop(tty_flag
, tty_flag
?
1216 options
.escape_char
: SSH_ESCAPECHAR_NONE
, id
);
1220 load_public_identity_files(void)
1222 char *filename
, *cp
, thishost
[NI_MAXHOST
];
1229 if (options
.smartcard_device
!= NULL
&&
1230 options
.num_identity_files
< SSH_MAX_IDENTITY_FILES
&&
1231 (keys
= sc_get_keys(options
.smartcard_device
, NULL
)) != NULL
) {
1233 for (i
= 0; keys
[i
] != NULL
; i
++) {
1235 memmove(&options
.identity_files
[1], &options
.identity_files
[0],
1236 sizeof(char *) * (SSH_MAX_IDENTITY_FILES
- 1));
1237 memmove(&options
.identity_keys
[1], &options
.identity_keys
[0],
1238 sizeof(Key
*) * (SSH_MAX_IDENTITY_FILES
- 1));
1239 options
.num_identity_files
++;
1240 options
.identity_keys
[0] = keys
[i
];
1241 options
.identity_files
[0] = sc_get_key_label(keys
[i
]);
1243 if (options
.num_identity_files
> SSH_MAX_IDENTITY_FILES
)
1244 options
.num_identity_files
= SSH_MAX_IDENTITY_FILES
;
1248 #endif /* SMARTCARD */
1249 if ((pw
= getpwuid(original_real_uid
)) == NULL
)
1250 fatal("load_public_identity_files: getpwuid failed");
1251 if (gethostname(thishost
, sizeof(thishost
)) == -1)
1252 fatal("load_public_identity_files: gethostname: %s",
1254 for (; i
< options
.num_identity_files
; i
++) {
1255 cp
= tilde_expand_filename(options
.identity_files
[i
],
1257 filename
= percent_expand(cp
, "d", pw
->pw_dir
,
1258 "u", pw
->pw_name
, "l", thishost
, "h", host
,
1259 "r", options
.user
, (char *)NULL
);
1261 public = key_load_public(filename
, NULL
);
1262 debug("identity file %s type %d", filename
,
1263 public ? public->type
: -1);
1264 xfree(options
.identity_files
[i
]);
1265 options
.identity_files
[i
] = filename
;
1266 options
.identity_keys
[i
] = public;
1271 control_client_sighandler(int signo
)
1273 control_client_terminate
= signo
;
1277 control_client_sigrelay(int signo
)
1279 if (control_server_pid
> 1)
1280 kill(control_server_pid
, signo
);
1284 env_permitted(char *env
)
1287 char name
[1024], *cp
;
1289 if ((cp
= strchr(env
, '=')) == NULL
|| cp
== env
)
1291 ret
= snprintf(name
, sizeof(name
), "%.*s", (int)(cp
- env
), env
);
1292 if (ret
<= 0 || (size_t)ret
>= sizeof(name
))
1293 fatal("env_permitted: name '%.100s...' too long", env
);
1295 for (i
= 0; i
< options
.num_send_env
; i
++)
1296 if (match_pattern(name
, options
.send_env
[i
]))
1303 control_client(const char *path
)
1305 struct sockaddr_un addr
;
1306 int i
, r
, fd
, sock
, exitval
, num_env
, addr_len
;
1309 extern char **environ
;
1312 if (mux_command
== 0)
1313 mux_command
= SSHMUX_COMMAND_OPEN
;
1315 switch (options
.control_master
) {
1316 case SSHCTL_MASTER_AUTO
:
1317 case SSHCTL_MASTER_AUTO_ASK
:
1318 debug("auto-mux: Trying existing master");
1320 case SSHCTL_MASTER_NO
:
1326 memset(&addr
, '\0', sizeof(addr
));
1327 addr
.sun_family
= AF_UNIX
;
1328 addr_len
= offsetof(struct sockaddr_un
, sun_path
) +
1331 if (strlcpy(addr
.sun_path
, path
,
1332 sizeof(addr
.sun_path
)) >= sizeof(addr
.sun_path
))
1333 fatal("ControlPath too long");
1335 if ((sock
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
1336 fatal("%s socket(): %s", __func__
, strerror(errno
));
1338 if (connect(sock
, (struct sockaddr
*)&addr
, addr_len
) == -1) {
1339 if (mux_command
!= SSHMUX_COMMAND_OPEN
) {
1340 fatal("Control socket connect(%.100s): %s", path
,
1343 if (errno
== ENOENT
)
1344 debug("Control socket \"%.100s\" does not exist", path
);
1346 error("Control socket connect(%.100s): %s", path
,
1353 if (stdin_null_flag
) {
1354 if ((fd
= open(_PATH_DEVNULL
, O_RDONLY
)) == -1)
1355 fatal("open(/dev/null): %s", strerror(errno
));
1356 if (dup2(fd
, STDIN_FILENO
) == -1)
1357 fatal("dup2: %s", strerror(errno
));
1358 if (fd
> STDERR_FILENO
)
1362 term
= getenv("TERM");
1366 flags
|= SSHMUX_FLAG_TTY
;
1368 flags
|= SSHMUX_FLAG_SUBSYS
;
1369 if (options
.forward_x11
)
1370 flags
|= SSHMUX_FLAG_X11_FWD
;
1371 if (options
.forward_agent
)
1372 flags
|= SSHMUX_FLAG_AGENT_FWD
;
1376 /* Send our command to server */
1377 buffer_put_int(&m
, mux_command
);
1378 buffer_put_int(&m
, flags
);
1379 if (ssh_msg_send(sock
, SSHMUX_VER
, &m
) == -1)
1380 fatal("%s: msg_send", __func__
);
1383 /* Get authorisation status and PID of controlee */
1384 if (ssh_msg_recv(sock
, &m
) == -1)
1385 fatal("%s: msg_recv", __func__
);
1386 if (buffer_get_char(&m
) != SSHMUX_VER
)
1387 fatal("%s: wrong version", __func__
);
1388 if (buffer_get_int(&m
) != 1)
1389 fatal("Connection to master denied");
1390 control_server_pid
= buffer_get_int(&m
);
1394 switch (mux_command
) {
1395 case SSHMUX_COMMAND_ALIVE_CHECK
:
1396 fprintf(stderr
, "Master running (pid=%d)\r\n",
1397 control_server_pid
);
1399 case SSHMUX_COMMAND_TERMINATE
:
1400 fprintf(stderr
, "Exit request sent.\r\n");
1402 case SSHMUX_COMMAND_OPEN
:
1403 /* continue below */
1406 fatal("silly mux_command %d", mux_command
);
1409 /* SSHMUX_COMMAND_OPEN */
1410 buffer_put_cstring(&m
, term
? term
: "");
1411 buffer_append(&command
, "\0", 1);
1412 buffer_put_cstring(&m
, buffer_ptr(&command
));
1414 if (options
.num_send_env
== 0 || environ
== NULL
) {
1415 buffer_put_int(&m
, 0);
1417 /* Pass environment */
1419 for (i
= 0; environ
[i
] != NULL
; i
++)
1420 if (env_permitted(environ
[i
]))
1421 num_env
++; /* Count */
1423 buffer_put_int(&m
, num_env
);
1425 for (i
= 0; environ
[i
] != NULL
&& num_env
>= 0; i
++)
1426 if (env_permitted(environ
[i
])) {
1428 buffer_put_cstring(&m
, environ
[i
]);
1432 if (ssh_msg_send(sock
, SSHMUX_VER
, &m
) == -1)
1433 fatal("%s: msg_send", __func__
);
1435 mm_send_fd(sock
, STDIN_FILENO
);
1436 mm_send_fd(sock
, STDOUT_FILENO
);
1437 mm_send_fd(sock
, STDERR_FILENO
);
1439 /* Wait for reply, so master has a chance to gather ttymodes */
1441 if (ssh_msg_recv(sock
, &m
) == -1)
1442 fatal("%s: msg_recv", __func__
);
1443 if (buffer_get_char(&m
) != SSHMUX_VER
)
1444 fatal("%s: wrong version", __func__
);
1447 signal(SIGHUP
, control_client_sighandler
);
1448 signal(SIGINT
, control_client_sighandler
);
1449 signal(SIGTERM
, control_client_sighandler
);
1450 signal(SIGWINCH
, control_client_sigrelay
);
1455 /* Stick around until the controlee closes the client_fd */
1457 for (;!control_client_terminate
;) {
1458 r
= read(sock
, &exitval
, sizeof(exitval
));
1460 debug2("Received EOF from master");
1464 debug2("Received exit status from master %d", exitval
);
1465 if (r
== -1 && errno
!= EINTR
)
1466 fatal("%s: read %s", __func__
, strerror(errno
));
1469 if (control_client_terminate
)
1470 debug2("Exiting on signal %d", control_client_terminate
);
1476 if (tty_flag
&& options
.log_level
!= SYSLOG_LEVEL_QUIET
)
1477 fprintf(stderr
, "Connection to master closed.\r\n");