1 /* $OpenBSD: ssh.c,v 1.294 2006/10/06 02:29:19 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 [-1246AaCfgkMNnqsTtVvXxY] [-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];
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:L: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 if (stat(optarg
, &st
) < 0) {
331 fprintf(stderr
, "Warning: Identity file %s "
332 "not accessible: %s.\n", optarg
,
336 if (options
.num_identity_files
>=
337 SSH_MAX_IDENTITY_FILES
)
338 fatal("Too many identity files specified "
339 "(max %d)", SSH_MAX_IDENTITY_FILES
);
340 options
.identity_files
[options
.num_identity_files
++] =
345 options
.smartcard_device
= xstrdup(optarg
);
347 fprintf(stderr
, "no support for smartcards.\n");
356 if (debug_flag
== 0) {
358 options
.log_level
= SYSLOG_LEVEL_DEBUG1
;
360 if (options
.log_level
< SYSLOG_LEVEL_DEBUG3
)
366 fprintf(stderr
, "%s, %s\n",
367 SSH_RELEASE
, SSLeay_version(SSLEAY_VERSION
));
372 if (options
.tun_open
== -1)
373 options
.tun_open
= SSH_TUNMODE_DEFAULT
;
374 options
.tun_local
= a2tun(optarg
, &options
.tun_remote
);
375 if (options
.tun_local
== SSH_TUNID_ERR
) {
376 fprintf(stderr
, "Bad tun device '%s'\n", optarg
);
381 options
.log_level
= SYSLOG_LEVEL_QUIET
;
384 if (optarg
[0] == '^' && optarg
[2] == 0 &&
385 (u_char
) optarg
[1] >= 64 &&
386 (u_char
) optarg
[1] < 128)
387 options
.escape_char
= (u_char
) optarg
[1] & 31;
388 else if (strlen(optarg
) == 1)
389 options
.escape_char
= (u_char
) optarg
[0];
390 else if (strcmp(optarg
, "none") == 0)
391 options
.escape_char
= SSH_ESCAPECHAR_NONE
;
393 fprintf(stderr
, "Bad escape character '%s'.\n",
399 if (ciphers_valid(optarg
)) {
401 options
.ciphers
= xstrdup(optarg
);
402 options
.cipher
= SSH_CIPHER_INVALID
;
405 options
.cipher
= cipher_number(optarg
);
406 if (options
.cipher
== -1) {
408 "Unknown cipher type '%s'\n",
412 if (options
.cipher
== SSH_CIPHER_3DES
)
413 options
.ciphers
= "3des-cbc";
414 else if (options
.cipher
== SSH_CIPHER_BLOWFISH
)
415 options
.ciphers
= "blowfish-cbc";
417 options
.ciphers
= (char *)-1;
421 if (mac_valid(optarg
))
422 options
.macs
= xstrdup(optarg
);
424 fprintf(stderr
, "Unknown mac type '%s'\n",
430 if (options
.control_master
== SSHCTL_MASTER_YES
)
431 options
.control_master
= SSHCTL_MASTER_ASK
;
433 options
.control_master
= SSHCTL_MASTER_YES
;
436 options
.port
= a2port(optarg
);
437 if (options
.port
== 0) {
438 fprintf(stderr
, "Bad port '%s'\n", optarg
);
443 options
.user
= optarg
;
447 if (parse_forward(&fwd
, optarg
))
448 add_local_forward(&options
, &fwd
);
451 "Bad local forwarding specification '%s'\n",
458 if (parse_forward(&fwd
, optarg
)) {
459 add_remote_forward(&options
, &fwd
);
462 "Bad remote forwarding specification "
469 cp
= p
= xstrdup(optarg
);
470 memset(&fwd
, '\0', sizeof(fwd
));
471 fwd
.connect_host
= "socks";
472 if ((fwd
.listen_host
= hpdelim(&cp
)) == NULL
) {
473 fprintf(stderr
, "Bad dynamic forwarding "
474 "specification '%.100s'\n", optarg
);
478 fwd
.listen_port
= a2port(cp
);
479 fwd
.listen_host
= cleanhostname(fwd
.listen_host
);
481 fwd
.listen_port
= a2port(fwd
.listen_host
);
482 fwd
.listen_host
= NULL
;
485 if (fwd
.listen_port
== 0) {
486 fprintf(stderr
, "Bad dynamic port '%s'\n",
490 add_local_forward(&options
, &fwd
);
495 options
.compression
= 1;
506 line
= xstrdup(optarg
);
507 if (process_config_line(&options
, host
? host
: "",
508 line
, "command-line", 0, &dummy
) != 0)
516 if (options
.control_path
!= NULL
)
517 free(options
.control_path
);
518 options
.control_path
= xstrdup(optarg
);
521 options
.bind_address
= optarg
;
534 if (ac
> 0 && !host
&& **av
!= '-') {
535 if (strrchr(*av
, '@')) {
537 cp
= strrchr(p
, '@');
538 if (cp
== NULL
|| cp
== p
)
546 optind
= optreset
= 1;
552 /* Check that we got a host name. */
556 SSLeay_add_all_algorithms();
557 ERR_load_crypto_strings();
559 /* Initialize the command to execute on remote host. */
560 buffer_init(&command
);
563 * Save the command to execute on the remote host in a buffer. There
564 * is no limit on the length of the command, except by the maximum
565 * packet size. Also sets the tty flag if there is no command.
568 /* No command specified - execute shell on a tty. */
570 if (subsystem_flag
) {
572 "You must specify a subsystem to invoke.\n");
576 /* A command has been specified. Store it into the buffer. */
577 for (i
= 0; i
< ac
; i
++) {
579 buffer_append(&command
, " ", 1);
580 buffer_append(&command
, av
[i
], strlen(av
[i
]));
584 /* Cannot fork to background if no command. */
585 if (fork_after_authentication_flag
&& buffer_len(&command
) == 0 && !no_shell_flag
)
586 fatal("Cannot fork into background without a command to execute.");
588 /* Allocate a tty by default if no command specified. */
589 if (buffer_len(&command
) == 0)
595 /* Do not allocate a tty if stdin is not a tty. */
596 if ((!isatty(fileno(stdin
)) || stdin_null_flag
) && !force_tty_flag
) {
598 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
603 * Initialize "log" output. Since we are the client all output
604 * actually goes to stderr.
606 log_init(av
[0], options
.log_level
== -1 ? SYSLOG_LEVEL_INFO
: options
.log_level
,
607 SYSLOG_FACILITY_USER
, 1);
610 * Read per-user configuration file. Ignore the system wide config
611 * file if the user specifies a config file on the command line.
613 if (config
!= NULL
) {
614 if (!read_config_file(config
, host
, &options
, 0))
615 fatal("Can't open user config file %.100s: "
616 "%.100s", config
, strerror(errno
));
618 snprintf(buf
, sizeof buf
, "%.100s/%.100s", pw
->pw_dir
,
619 _PATH_SSH_USER_CONFFILE
);
620 (void)read_config_file(buf
, host
, &options
, 1);
622 /* Read systemwide configuration file after use config. */
623 (void)read_config_file(_PATH_HOST_CONFIG_FILE
, host
,
627 /* Fill configuration defaults. */
628 fill_default_options(&options
);
630 channel_set_af(options
.address_family
);
633 log_init(av
[0], options
.log_level
, SYSLOG_FACILITY_USER
, 1);
637 if (options
.user
== NULL
)
638 options
.user
= xstrdup(pw
->pw_name
);
640 if (options
.hostname
!= NULL
)
641 host
= options
.hostname
;
643 /* force lowercase for hostkey matching */
644 if (options
.host_key_alias
!= NULL
) {
645 for (p
= options
.host_key_alias
; *p
; p
++)
647 *p
= (char)tolower(*p
);
650 /* Get default port if port has not been set. */
651 if (options
.port
== 0) {
652 sp
= getservbyname(SSH_SERVICE_NAME
, "tcp");
653 options
.port
= sp
? ntohs(sp
->s_port
) : SSH_DEFAULT_PORT
;
656 if (options
.proxy_command
!= NULL
&&
657 strcmp(options
.proxy_command
, "none") == 0)
658 options
.proxy_command
= NULL
;
659 if (options
.control_path
!= NULL
&&
660 strcmp(options
.control_path
, "none") == 0)
661 options
.control_path
= NULL
;
663 if (options
.control_path
!= NULL
) {
664 char thishost
[NI_MAXHOST
];
666 if (gethostname(thishost
, sizeof(thishost
)) == -1)
667 fatal("gethostname: %s", strerror(errno
));
668 snprintf(buf
, sizeof(buf
), "%d", options
.port
);
669 cp
= tilde_expand_filename(options
.control_path
,
671 options
.control_path
= percent_expand(cp
, "p", buf
, "h", host
,
672 "r", options
.user
, "l", thishost
, (char *)NULL
);
675 if (mux_command
!= 0 && options
.control_path
== NULL
)
676 fatal("No ControlPath specified for \"-O\" command");
677 if (options
.control_path
!= NULL
)
678 control_client(options
.control_path
);
680 /* Open a connection to the remote host. */
681 if (ssh_connect(host
, &hostaddr
, options
.port
,
682 options
.address_family
, options
.connection_attempts
,
684 options
.use_privileged_port
,
686 original_effective_uid
== 0 && options
.use_privileged_port
,
688 options
.proxy_command
) != 0)
692 * If we successfully made the connection, load the host private key
693 * in case we will need it later for combined rsa-rhosts
694 * authentication. This must be done before releasing extra
695 * privileges, because the file is only readable by root.
696 * If we cannot access the private keys, load the public keys
697 * instead and try to execute the ssh-keysign helper instead.
699 sensitive_data
.nkeys
= 0;
700 sensitive_data
.keys
= NULL
;
701 sensitive_data
.external_keysign
= 0;
702 if (options
.rhosts_rsa_authentication
||
703 options
.hostbased_authentication
) {
704 sensitive_data
.nkeys
= 3;
705 sensitive_data
.keys
= xcalloc(sensitive_data
.nkeys
,
709 sensitive_data
.keys
[0] = key_load_private_type(KEY_RSA1
,
710 _PATH_HOST_KEY_FILE
, "", NULL
, NULL
);
711 sensitive_data
.keys
[1] = key_load_private_type(KEY_DSA
,
712 _PATH_HOST_DSA_KEY_FILE
, "", NULL
, NULL
);
713 sensitive_data
.keys
[2] = key_load_private_type(KEY_RSA
,
714 _PATH_HOST_RSA_KEY_FILE
, "", NULL
, NULL
);
717 if (options
.hostbased_authentication
== 1 &&
718 sensitive_data
.keys
[0] == NULL
&&
719 sensitive_data
.keys
[1] == NULL
&&
720 sensitive_data
.keys
[2] == NULL
) {
721 sensitive_data
.keys
[1] = key_load_public(
722 _PATH_HOST_DSA_KEY_FILE
, NULL
);
723 sensitive_data
.keys
[2] = key_load_public(
724 _PATH_HOST_RSA_KEY_FILE
, NULL
);
725 sensitive_data
.external_keysign
= 1;
729 * Get rid of any extra privileges that we may have. We will no
730 * longer need them. Also, extra privileges could make it very hard
731 * to read identity files and other non-world-readable files from the
732 * user's home directory if it happens to be on a NFS volume where
733 * root is mapped to nobody.
735 if (original_effective_uid
== 0) {
737 permanently_set_uid(pw
);
741 * Now that we are back to our own permissions, create ~/.ssh
742 * directory if it doesn't already exist.
744 snprintf(buf
, sizeof buf
, "%.100s%s%.100s", pw
->pw_dir
, strcmp(pw
->pw_dir
, "/") ? "/" : "", _PATH_SSH_USER_DIR
);
745 if (stat(buf
, &st
) < 0)
746 if (mkdir(buf
, 0700) < 0)
747 error("Could not create directory '%.200s'.", buf
);
749 /* load options.identity_files */
750 load_public_identity_files();
752 /* Expand ~ in known host file names. */
754 options
.system_hostfile
=
755 tilde_expand_filename(options
.system_hostfile
, original_real_uid
);
756 options
.user_hostfile
=
757 tilde_expand_filename(options
.user_hostfile
, original_real_uid
);
758 options
.system_hostfile2
=
759 tilde_expand_filename(options
.system_hostfile2
, original_real_uid
);
760 options
.user_hostfile2
=
761 tilde_expand_filename(options
.user_hostfile2
, original_real_uid
);
763 signal(SIGPIPE
, SIG_IGN
); /* ignore SIGPIPE early */
765 /* Log into the remote system. This never returns if the login fails. */
766 ssh_login(&sensitive_data
, host
, (struct sockaddr
*)&hostaddr
, pw
);
768 /* We no longer need the private host keys. Clear them now. */
769 if (sensitive_data
.nkeys
!= 0) {
770 for (i
= 0; i
< sensitive_data
.nkeys
; i
++) {
771 if (sensitive_data
.keys
[i
] != NULL
) {
772 /* Destroys contents safely */
773 debug3("clear hostkey %d", i
);
774 key_free(sensitive_data
.keys
[i
]);
775 sensitive_data
.keys
[i
] = NULL
;
778 xfree(sensitive_data
.keys
);
780 for (i
= 0; i
< options
.num_identity_files
; i
++) {
781 if (options
.identity_files
[i
]) {
782 xfree(options
.identity_files
[i
]);
783 options
.identity_files
[i
] = NULL
;
785 if (options
.identity_keys
[i
]) {
786 key_free(options
.identity_keys
[i
]);
787 options
.identity_keys
[i
] = NULL
;
791 exit_status
= compat20
? ssh_session2() : ssh_session();
794 if (options
.control_path
!= NULL
&& control_fd
!= -1)
795 unlink(options
.control_path
);
798 * Send SIGHUP to proxy command if used. We don't wait() in
799 * case it hangs and instead rely on init to reap the child
801 if (proxy_command_pid
> 1)
802 kill(proxy_command_pid
, SIGHUP
);
808 ssh_init_forwarding(void)
813 /* Initiate local TCP/IP port forwardings. */
814 for (i
= 0; i
< options
.num_local_forwards
; i
++) {
815 debug("Local connections to %.200s:%d forwarded to remote "
817 (options
.local_forwards
[i
].listen_host
== NULL
) ?
818 (options
.gateway_ports
? "*" : "LOCALHOST") :
819 options
.local_forwards
[i
].listen_host
,
820 options
.local_forwards
[i
].listen_port
,
821 options
.local_forwards
[i
].connect_host
,
822 options
.local_forwards
[i
].connect_port
);
823 success
+= channel_setup_local_fwd_listener(
824 options
.local_forwards
[i
].listen_host
,
825 options
.local_forwards
[i
].listen_port
,
826 options
.local_forwards
[i
].connect_host
,
827 options
.local_forwards
[i
].connect_port
,
828 options
.gateway_ports
);
830 if (i
> 0 && success
!= i
&& options
.exit_on_forward_failure
)
831 fatal("Could not request local forwarding.");
832 if (i
> 0 && success
== 0)
833 error("Could not request local forwarding.");
835 /* Initiate remote TCP/IP port forwardings. */
836 for (i
= 0; i
< options
.num_remote_forwards
; i
++) {
837 debug("Remote connections from %.200s:%d forwarded to "
838 "local address %.200s:%d",
839 (options
.remote_forwards
[i
].listen_host
== NULL
) ?
840 "LOCALHOST" : options
.remote_forwards
[i
].listen_host
,
841 options
.remote_forwards
[i
].listen_port
,
842 options
.remote_forwards
[i
].connect_host
,
843 options
.remote_forwards
[i
].connect_port
);
844 if (channel_request_remote_forwarding(
845 options
.remote_forwards
[i
].listen_host
,
846 options
.remote_forwards
[i
].listen_port
,
847 options
.remote_forwards
[i
].connect_host
,
848 options
.remote_forwards
[i
].connect_port
) < 0) {
849 if (options
.exit_on_forward_failure
)
850 fatal("Could not request remote forwarding.");
852 logit("Warning: Could not request remote "
859 check_agent_present(void)
861 if (options
.forward_agent
) {
862 /* Clear agent forwarding if we don't have an agent. */
863 if (!ssh_agent_present())
864 options
.forward_agent
= 0;
878 /* Enable compression if requested. */
879 if (options
.compression
) {
880 debug("Requesting compression at level %d.", options
.compression_level
);
882 if (options
.compression_level
< 1 || options
.compression_level
> 9)
883 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
885 /* Send the request. */
886 packet_start(SSH_CMSG_REQUEST_COMPRESSION
);
887 packet_put_int(options
.compression_level
);
890 type
= packet_read();
891 if (type
== SSH_SMSG_SUCCESS
)
892 packet_start_compression(options
.compression_level
);
893 else if (type
== SSH_SMSG_FAILURE
)
894 logit("Warning: Remote host refused compression.");
896 packet_disconnect("Protocol error waiting for compression response.");
898 /* Allocate a pseudo tty if appropriate. */
900 debug("Requesting pty.");
902 /* Start the packet. */
903 packet_start(SSH_CMSG_REQUEST_PTY
);
905 /* Store TERM in the packet. There is no limit on the
906 length of the string. */
910 packet_put_cstring(cp
);
912 /* Store window size in the packet. */
913 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) < 0)
914 memset(&ws
, 0, sizeof(ws
));
915 packet_put_int((u_int
)ws
.ws_row
);
916 packet_put_int((u_int
)ws
.ws_col
);
917 packet_put_int((u_int
)ws
.ws_xpixel
);
918 packet_put_int((u_int
)ws
.ws_ypixel
);
920 /* Store tty modes in the packet. */
921 tty_make_modes(fileno(stdin
), NULL
);
923 /* Send the packet, and wait for it to leave. */
927 /* Read response from the server. */
928 type
= packet_read();
929 if (type
== SSH_SMSG_SUCCESS
) {
932 } else if (type
== SSH_SMSG_FAILURE
)
933 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
935 packet_disconnect("Protocol error waiting for pty request response.");
937 /* Request X11 forwarding if enabled and DISPLAY is set. */
938 display
= getenv("DISPLAY");
939 if (options
.forward_x11
&& display
!= NULL
) {
941 /* Get reasonable local authentication information. */
942 client_x11_get_proto(display
, options
.xauth_location
,
943 options
.forward_x11_trusted
, &proto
, &data
);
944 /* Request forwarding with authentication spoofing. */
945 debug("Requesting X11 forwarding with authentication spoofing.");
946 x11_request_forwarding_with_spoofing(0, display
, proto
, data
);
948 /* Read response from the server. */
949 type
= packet_read();
950 if (type
== SSH_SMSG_SUCCESS
) {
952 } else if (type
== SSH_SMSG_FAILURE
) {
953 logit("Warning: Remote host denied X11 forwarding.");
955 packet_disconnect("Protocol error waiting for X11 forwarding");
958 /* Tell the packet module whether this is an interactive session. */
959 packet_set_interactive(interactive
);
961 /* Request authentication agent forwarding if appropriate. */
962 check_agent_present();
964 if (options
.forward_agent
) {
965 debug("Requesting authentication agent forwarding.");
966 auth_request_forwarding();
968 /* Read response from the server. */
969 type
= packet_read();
971 if (type
!= SSH_SMSG_SUCCESS
)
972 logit("Warning: Remote host denied authentication agent forwarding.");
975 /* Initiate port forwardings. */
976 ssh_init_forwarding();
978 /* If requested, let ssh continue in the background. */
979 if (fork_after_authentication_flag
)
980 if (daemon(1, 1) < 0)
981 fatal("daemon() failed: %.200s", strerror(errno
));
984 * If a command was specified on the command line, execute the
985 * command now. Otherwise request the server to start a shell.
987 if (buffer_len(&command
) > 0) {
988 int len
= buffer_len(&command
);
991 debug("Sending command: %.*s", len
, (u_char
*)buffer_ptr(&command
));
992 packet_start(SSH_CMSG_EXEC_CMD
);
993 packet_put_string(buffer_ptr(&command
), buffer_len(&command
));
997 debug("Requesting shell.");
998 packet_start(SSH_CMSG_EXEC_SHELL
);
1000 packet_write_wait();
1003 /* Enter the interactive session. */
1004 return client_loop(have_tty
, tty_flag
?
1005 options
.escape_char
: SSH_ESCAPECHAR_NONE
, 0);
1009 ssh_subsystem_reply(int type
, u_int32_t seq
, void *ctxt
)
1013 id
= packet_get_int();
1014 len
= buffer_len(&command
);
1018 if (type
== SSH2_MSG_CHANNEL_FAILURE
)
1019 fatal("Request for subsystem '%.*s' failed on channel %d",
1020 len
, (u_char
*)buffer_ptr(&command
), id
);
1024 client_global_request_reply_fwd(int type
, u_int32_t seq
, void *ctxt
)
1028 i
= client_global_request_id
++;
1029 if (i
>= options
.num_remote_forwards
)
1031 debug("remote forward %s for: listen %d, connect %s:%d",
1032 type
== SSH2_MSG_REQUEST_SUCCESS
? "success" : "failure",
1033 options
.remote_forwards
[i
].listen_port
,
1034 options
.remote_forwards
[i
].connect_host
,
1035 options
.remote_forwards
[i
].connect_port
);
1036 if (type
== SSH2_MSG_REQUEST_FAILURE
) {
1037 if (options
.exit_on_forward_failure
)
1038 fatal("Error: remote port forwarding failed for "
1040 options
.remote_forwards
[i
].listen_port
);
1042 logit("Warning: remote port forwarding failed for "
1044 options
.remote_forwards
[i
].listen_port
);
1049 ssh_control_listener(void)
1051 struct sockaddr_un addr
;
1055 if (options
.control_path
== NULL
||
1056 options
.control_master
== SSHCTL_MASTER_NO
)
1059 debug("setting up multiplex master socket");
1061 memset(&addr
, '\0', sizeof(addr
));
1062 addr
.sun_family
= AF_UNIX
;
1063 addr_len
= offsetof(struct sockaddr_un
, sun_path
) +
1064 strlen(options
.control_path
) + 1;
1066 if (strlcpy(addr
.sun_path
, options
.control_path
,
1067 sizeof(addr
.sun_path
)) >= sizeof(addr
.sun_path
))
1068 fatal("ControlPath too long");
1070 if ((control_fd
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
1071 fatal("%s socket(): %s", __func__
, strerror(errno
));
1073 old_umask
= umask(0177);
1074 if (bind(control_fd
, (struct sockaddr
*)&addr
, addr_len
) == -1) {
1076 if (errno
== EINVAL
|| errno
== EADDRINUSE
)
1077 fatal("ControlSocket %s already exists",
1078 options
.control_path
);
1080 fatal("%s bind(): %s", __func__
, strerror(errno
));
1084 if (listen(control_fd
, 64) == -1)
1085 fatal("%s listen(): %s", __func__
, strerror(errno
));
1087 set_nonblock(control_fd
);
1090 /* request pty/x11/agent/tcpfwd/shell for channel */
1092 ssh_session2_setup(int id
, void *arg
)
1094 extern char **environ
;
1095 const char *display
;
1096 int interactive
= tty_flag
;
1098 display
= getenv("DISPLAY");
1099 if (options
.forward_x11
&& display
!= NULL
) {
1101 /* Get reasonable local authentication information. */
1102 client_x11_get_proto(display
, options
.xauth_location
,
1103 options
.forward_x11_trusted
, &proto
, &data
);
1104 /* Request forwarding with authentication spoofing. */
1105 debug("Requesting X11 forwarding with authentication spoofing.");
1106 x11_request_forwarding_with_spoofing(id
, display
, proto
, data
);
1108 /* XXX wait for reply */
1111 check_agent_present();
1112 if (options
.forward_agent
) {
1113 debug("Requesting authentication agent forwarding.");
1114 channel_request_start(id
, "auth-agent-req@openssh.com", 0);
1118 if (options
.tun_open
!= SSH_TUNMODE_NO
) {
1122 debug("Requesting tun.");
1123 if ((fd
= tun_open(options
.tun_local
,
1124 options
.tun_open
)) >= 0) {
1125 c
= channel_new("tun", SSH_CHANNEL_OPENING
, fd
, fd
, -1,
1126 CHAN_TCP_WINDOW_DEFAULT
, CHAN_TCP_PACKET_DEFAULT
,
1129 #if defined(SSH_TUN_FILTER)
1130 if (options
.tun_open
== SSH_TUNMODE_POINTOPOINT
)
1131 channel_register_filter(c
->self
, sys_tun_infilter
,
1134 packet_start(SSH2_MSG_CHANNEL_OPEN
);
1135 packet_put_cstring("tun@openssh.com");
1136 packet_put_int(c
->self
);
1137 packet_put_int(c
->local_window_max
);
1138 packet_put_int(c
->local_maxpacket
);
1139 packet_put_int(options
.tun_open
);
1140 packet_put_int(options
.tun_remote
);
1145 client_session2_setup(id
, tty_flag
, subsystem_flag
, getenv("TERM"),
1146 NULL
, fileno(stdin
), &command
, environ
, &ssh_subsystem_reply
);
1148 packet_set_interactive(interactive
);
1151 /* open new channel for a session */
1153 ssh_session2_open(void)
1156 int window
, packetmax
, in
, out
, err
;
1158 if (stdin_null_flag
) {
1159 in
= open(_PATH_DEVNULL
, O_RDONLY
);
1161 in
= dup(STDIN_FILENO
);
1163 out
= dup(STDOUT_FILENO
);
1164 err
= dup(STDERR_FILENO
);
1166 if (in
< 0 || out
< 0 || err
< 0)
1167 fatal("dup() in/out/err failed");
1169 /* enable nonblocking unless tty */
1177 window
= CHAN_SES_WINDOW_DEFAULT
;
1178 packetmax
= CHAN_SES_PACKET_DEFAULT
;
1184 "session", SSH_CHANNEL_OPENING
, in
, out
, err
,
1185 window
, packetmax
, CHAN_EXTENDED_WRITE
,
1186 "client-session", /*nonblock*/0);
1188 debug3("ssh_session2_open: channel_new: %d", c
->self
);
1190 channel_send_open(c
->self
);
1192 channel_register_confirm(c
->self
, ssh_session2_setup
, NULL
);
1202 /* XXX should be pre-session */
1203 ssh_init_forwarding();
1204 ssh_control_listener();
1206 if (!no_shell_flag
|| (datafellows
& SSH_BUG_DUMMYCHAN
))
1207 id
= ssh_session2_open();
1209 /* Execute a local command */
1210 if (options
.local_command
!= NULL
&&
1211 options
.permit_local_command
)
1212 ssh_local_cmd(options
.local_command
);
1214 /* If requested, let ssh continue in the background. */
1215 if (fork_after_authentication_flag
)
1216 if (daemon(1, 1) < 0)
1217 fatal("daemon() failed: %.200s", strerror(errno
));
1219 return client_loop(tty_flag
, tty_flag
?
1220 options
.escape_char
: SSH_ESCAPECHAR_NONE
, id
);
1224 load_public_identity_files(void)
1226 char *filename
, *cp
, thishost
[NI_MAXHOST
];
1233 if (options
.smartcard_device
!= NULL
&&
1234 options
.num_identity_files
< SSH_MAX_IDENTITY_FILES
&&
1235 (keys
= sc_get_keys(options
.smartcard_device
, NULL
)) != NULL
) {
1237 for (i
= 0; keys
[i
] != NULL
; i
++) {
1239 memmove(&options
.identity_files
[1], &options
.identity_files
[0],
1240 sizeof(char *) * (SSH_MAX_IDENTITY_FILES
- 1));
1241 memmove(&options
.identity_keys
[1], &options
.identity_keys
[0],
1242 sizeof(Key
*) * (SSH_MAX_IDENTITY_FILES
- 1));
1243 options
.num_identity_files
++;
1244 options
.identity_keys
[0] = keys
[i
];
1245 options
.identity_files
[0] = sc_get_key_label(keys
[i
]);
1247 if (options
.num_identity_files
> SSH_MAX_IDENTITY_FILES
)
1248 options
.num_identity_files
= SSH_MAX_IDENTITY_FILES
;
1252 #endif /* SMARTCARD */
1253 if ((pw
= getpwuid(original_real_uid
)) == NULL
)
1254 fatal("load_public_identity_files: getpwuid failed");
1255 if (gethostname(thishost
, sizeof(thishost
)) == -1)
1256 fatal("load_public_identity_files: gethostname: %s",
1258 for (; i
< options
.num_identity_files
; i
++) {
1259 cp
= tilde_expand_filename(options
.identity_files
[i
],
1261 filename
= percent_expand(cp
, "d", pw
->pw_dir
,
1262 "u", pw
->pw_name
, "l", thishost
, "h", host
,
1263 "r", options
.user
, (char *)NULL
);
1265 public = key_load_public(filename
, NULL
);
1266 debug("identity file %s type %d", filename
,
1267 public ? public->type
: -1);
1268 xfree(options
.identity_files
[i
]);
1269 options
.identity_files
[i
] = filename
;
1270 options
.identity_keys
[i
] = public;
1275 control_client_sighandler(int signo
)
1277 control_client_terminate
= signo
;
1281 control_client_sigrelay(int signo
)
1283 if (control_server_pid
> 1)
1284 kill(control_server_pid
, signo
);
1288 env_permitted(char *env
)
1291 char name
[1024], *cp
;
1293 if ((cp
= strchr(env
, '=')) == NULL
|| cp
== env
)
1295 ret
= snprintf(name
, sizeof(name
), "%.*s", (int)(cp
- env
), env
);
1296 if (ret
<= 0 || (size_t)ret
>= sizeof(name
))
1297 fatal("env_permitted: name '%.100s...' too long", env
);
1299 for (i
= 0; i
< options
.num_send_env
; i
++)
1300 if (match_pattern(name
, options
.send_env
[i
]))
1307 control_client(const char *path
)
1309 struct sockaddr_un addr
;
1310 int i
, r
, fd
, sock
, exitval
, num_env
, addr_len
;
1313 extern char **environ
;
1316 if (mux_command
== 0)
1317 mux_command
= SSHMUX_COMMAND_OPEN
;
1319 switch (options
.control_master
) {
1320 case SSHCTL_MASTER_AUTO
:
1321 case SSHCTL_MASTER_AUTO_ASK
:
1322 debug("auto-mux: Trying existing master");
1324 case SSHCTL_MASTER_NO
:
1330 memset(&addr
, '\0', sizeof(addr
));
1331 addr
.sun_family
= AF_UNIX
;
1332 addr_len
= offsetof(struct sockaddr_un
, sun_path
) +
1335 if (strlcpy(addr
.sun_path
, path
,
1336 sizeof(addr
.sun_path
)) >= sizeof(addr
.sun_path
))
1337 fatal("ControlPath too long");
1339 if ((sock
= socket(PF_UNIX
, SOCK_STREAM
, 0)) < 0)
1340 fatal("%s socket(): %s", __func__
, strerror(errno
));
1342 if (connect(sock
, (struct sockaddr
*)&addr
, addr_len
) == -1) {
1343 if (mux_command
!= SSHMUX_COMMAND_OPEN
) {
1344 fatal("Control socket connect(%.100s): %s", path
,
1347 if (errno
== ENOENT
)
1348 debug("Control socket \"%.100s\" does not exist", path
);
1350 error("Control socket connect(%.100s): %s", path
,
1357 if (stdin_null_flag
) {
1358 if ((fd
= open(_PATH_DEVNULL
, O_RDONLY
)) == -1)
1359 fatal("open(/dev/null): %s", strerror(errno
));
1360 if (dup2(fd
, STDIN_FILENO
) == -1)
1361 fatal("dup2: %s", strerror(errno
));
1362 if (fd
> STDERR_FILENO
)
1366 term
= getenv("TERM");
1370 flags
|= SSHMUX_FLAG_TTY
;
1372 flags
|= SSHMUX_FLAG_SUBSYS
;
1373 if (options
.forward_x11
)
1374 flags
|= SSHMUX_FLAG_X11_FWD
;
1375 if (options
.forward_agent
)
1376 flags
|= SSHMUX_FLAG_AGENT_FWD
;
1380 /* Send our command to server */
1381 buffer_put_int(&m
, mux_command
);
1382 buffer_put_int(&m
, flags
);
1383 if (ssh_msg_send(sock
, SSHMUX_VER
, &m
) == -1)
1384 fatal("%s: msg_send", __func__
);
1387 /* Get authorisation status and PID of controlee */
1388 if (ssh_msg_recv(sock
, &m
) == -1)
1389 fatal("%s: msg_recv", __func__
);
1390 if (buffer_get_char(&m
) != SSHMUX_VER
)
1391 fatal("%s: wrong version", __func__
);
1392 if (buffer_get_int(&m
) != 1)
1393 fatal("Connection to master denied");
1394 control_server_pid
= buffer_get_int(&m
);
1398 switch (mux_command
) {
1399 case SSHMUX_COMMAND_ALIVE_CHECK
:
1400 fprintf(stderr
, "Master running (pid=%d)\r\n",
1401 control_server_pid
);
1403 case SSHMUX_COMMAND_TERMINATE
:
1404 fprintf(stderr
, "Exit request sent.\r\n");
1406 case SSHMUX_COMMAND_OPEN
:
1407 /* continue below */
1410 fatal("silly mux_command %d", mux_command
);
1413 /* SSHMUX_COMMAND_OPEN */
1414 buffer_put_cstring(&m
, term
? term
: "");
1415 buffer_append(&command
, "\0", 1);
1416 buffer_put_cstring(&m
, buffer_ptr(&command
));
1418 if (options
.num_send_env
== 0 || environ
== NULL
) {
1419 buffer_put_int(&m
, 0);
1421 /* Pass environment */
1423 for (i
= 0; environ
[i
] != NULL
; i
++)
1424 if (env_permitted(environ
[i
]))
1425 num_env
++; /* Count */
1427 buffer_put_int(&m
, num_env
);
1429 for (i
= 0; environ
[i
] != NULL
&& num_env
>= 0; i
++)
1430 if (env_permitted(environ
[i
])) {
1432 buffer_put_cstring(&m
, environ
[i
]);
1436 if (ssh_msg_send(sock
, SSHMUX_VER
, &m
) == -1)
1437 fatal("%s: msg_send", __func__
);
1439 mm_send_fd(sock
, STDIN_FILENO
);
1440 mm_send_fd(sock
, STDOUT_FILENO
);
1441 mm_send_fd(sock
, STDERR_FILENO
);
1443 /* Wait for reply, so master has a chance to gather ttymodes */
1445 if (ssh_msg_recv(sock
, &m
) == -1)
1446 fatal("%s: msg_recv", __func__
);
1447 if (buffer_get_char(&m
) != SSHMUX_VER
)
1448 fatal("%s: wrong version", __func__
);
1451 signal(SIGHUP
, control_client_sighandler
);
1452 signal(SIGINT
, control_client_sighandler
);
1453 signal(SIGTERM
, control_client_sighandler
);
1454 signal(SIGWINCH
, control_client_sigrelay
);
1459 /* Stick around until the controlee closes the client_fd */
1461 for (;!control_client_terminate
;) {
1462 r
= read(sock
, &exitval
, sizeof(exitval
));
1464 debug2("Received EOF from master");
1468 debug2("Received exit status from master %d", exitval
);
1469 if (r
== -1 && errno
!= EINTR
)
1470 fatal("%s: read %s", __func__
, strerror(errno
));
1473 if (control_client_terminate
)
1474 debug2("Exiting on signal %d", control_client_terminate
);
1480 if (tty_flag
&& options
.log_level
!= SYSLOG_LEVEL_QUIET
)
1481 fprintf(stderr
, "Connection to master closed.\r\n");