1 /* $OpenBSD: ssh.c,v 1.332 2010/01/26 01:28:35 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/param.h>
52 #include <sys/socket.h>
70 #include <netinet/in.h>
71 #include <arpa/inet.h>
73 #include <openssl/evp.h>
74 #include <openssl/err.h>
75 #include "openbsd-compat/openssl-compat.h"
76 #include "openbsd-compat/sys-queue.h"
90 #include "pathnames.h"
92 #include "clientloop.h"
95 #include "sshconnect.h"
110 extern char *__progname
;
112 /* Flag indicating whether debug mode is on. May be set on the command line. */
115 /* Flag indicating whether a tty should be allocated */
118 int force_tty_flag
= 0;
120 /* don't exec a shell */
121 int no_shell_flag
= 0;
124 * Flag indicating that nothing should be read from stdin. This can be set
125 * on the command line.
127 int stdin_null_flag
= 0;
130 * Flag indicating that ssh should fork after authentication. This is useful
131 * so that the passphrase can be entered manually, and then ssh goes to the
134 int fork_after_authentication_flag
= 0;
136 /* forward stdio to remote host and port */
137 char *stdio_forward_host
= NULL
;
138 int stdio_forward_port
= 0;
141 * General data structure for command line options and options configurable
142 * in configuration files. See readconf.h.
146 /* optional user configfile */
150 * Name of the host we are connecting to. This is the name given on the
151 * command line, or the HostName specified for the user-supplied name in a
152 * configuration file.
156 /* socket address the host resolves to */
157 struct sockaddr_storage hostaddr
;
159 /* Private host keys. */
160 Sensitive sensitive_data
;
162 /* Original real UID. */
163 uid_t original_real_uid
;
164 uid_t original_effective_uid
;
166 /* command to be executed */
169 /* Should we execute a command or invoke a subsystem? */
170 int subsystem_flag
= 0;
172 /* # of replies received for global requests */
173 static int remote_forward_confirms_received
= 0;
175 /* pid of proxycommand child process */
176 pid_t proxy_command_pid
= 0;
179 extern int muxserver_sock
;
180 extern u_int muxclient_command
;
182 /* Prints a help message to the user. This function never returns. */
188 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-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 host:port] [-w local_tun[:remote_tun]]\n"
194 " [user@]hostname [command]\n"
199 static int ssh_session(void);
200 static int ssh_session2(void);
201 static void load_public_identity_files(void);
203 /* from muxclient.c */
204 void muxclient(const char *);
205 void muxserver_listen(void);
208 * Main program for the ssh client.
211 main(int ac
, char **av
)
213 int i
, r
, opt
, exit_status
, use_syslog
;
214 char *p
, *cp
, *line
, *argv0
, buf
[MAXPATHLEN
];
217 int dummy
, timeout_ms
;
218 extern int optind
, optreset
;
223 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
226 __progname
= ssh_get_progname(av
[0]);
230 * Save the original real uid. It will be needed later (uid-swapping
231 * may clobber the real uid).
233 original_real_uid
= getuid();
234 original_effective_uid
= geteuid();
237 * Use uid-swapping to give up root privileges for the duration of
238 * option processing. We will re-instantiate the rights when we are
239 * ready to create the privileged port, and will permanently drop
240 * them when the port has been created (actually, when the connection
241 * has been made, as we may need to create the port several times).
245 #ifdef HAVE_SETRLIMIT
246 /* If we are installed setuid root be careful to not drop core. */
247 if (original_real_uid
!= original_effective_uid
) {
249 rlim
.rlim_cur
= rlim
.rlim_max
= 0;
250 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
251 fatal("setrlimit failed: %.100s", strerror(errno
));
255 pw
= getpwuid(original_real_uid
);
257 logit("You don't exist, go away!");
260 /* Take a copy of the returned structure. */
264 * Set our umask to something reasonable, as some files are created
265 * with the default umask. This will make them world-readable but
266 * writable only by the owner, which is ok for all files for which we
267 * don't set the modes explicitly.
272 * Initialize option structure to indicate that no values have been
275 initialize_options(&options
);
277 /* Parse command-line arguments. */
283 while ((opt
= getopt(ac
, av
, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
284 "ACD:F:I:KL:MNO:PR:S:TVw:W:XYy")) != -1) {
287 options
.protocol
= SSH_PROTO_1
;
290 options
.protocol
= SSH_PROTO_2
;
293 options
.address_family
= AF_INET
;
296 options
.address_family
= AF_INET6
;
302 fork_after_authentication_flag
= 1;
306 options
.forward_x11
= 0;
309 options
.forward_x11
= 1;
315 options
.forward_x11
= 1;
316 options
.forward_x11_trusted
= 1;
319 options
.gateway_ports
= 1;
322 if (stdio_forward_host
!= NULL
)
323 fatal("Cannot specify multiplexing "
325 else if (muxclient_command
!= 0)
326 fatal("Multiplexing command already specified");
327 if (strcmp(optarg
, "check") == 0)
328 muxclient_command
= SSHMUX_COMMAND_ALIVE_CHECK
;
329 else if (strcmp(optarg
, "exit") == 0)
330 muxclient_command
= SSHMUX_COMMAND_TERMINATE
;
332 fatal("Invalid multiplex command.");
334 case 'P': /* deprecated */
335 options
.use_privileged_port
= 0;
338 options
.forward_agent
= 0;
341 options
.forward_agent
= 1;
344 options
.gss_deleg_creds
= 0;
347 options
.gss_authentication
= 1;
348 options
.gss_deleg_creds
= 1;
351 if (stat(optarg
, &st
) < 0) {
352 fprintf(stderr
, "Warning: Identity file %s "
353 "not accessible: %s.\n", optarg
,
357 if (options
.num_identity_files
>=
358 SSH_MAX_IDENTITY_FILES
)
359 fatal("Too many identity files specified "
360 "(max %d)", SSH_MAX_IDENTITY_FILES
);
361 options
.identity_files
[options
.num_identity_files
++] =
366 options
.smartcard_device
= xstrdup(optarg
);
368 fprintf(stderr
, "no support for smartcards.\n");
377 if (debug_flag
== 0) {
379 options
.log_level
= SYSLOG_LEVEL_DEBUG1
;
381 if (options
.log_level
< SYSLOG_LEVEL_DEBUG3
)
387 fprintf(stderr
, "%s, %s\n",
388 SSH_RELEASE
, SSLeay_version(SSLEAY_VERSION
));
393 if (options
.tun_open
== -1)
394 options
.tun_open
= SSH_TUNMODE_DEFAULT
;
395 options
.tun_local
= a2tun(optarg
, &options
.tun_remote
);
396 if (options
.tun_local
== SSH_TUNID_ERR
) {
398 "Bad tun device '%s'\n", optarg
);
403 if (stdio_forward_host
!= NULL
)
404 fatal("stdio forward already specified");
405 if (muxclient_command
!= 0)
406 fatal("Cannot specify stdio forward with -O");
407 if (parse_forward(&fwd
, optarg
, 1, 0)) {
408 stdio_forward_host
= fwd
.listen_host
;
409 stdio_forward_port
= fwd
.listen_port
;
410 xfree(fwd
.connect_host
);
413 "Bad stdio forwarding specification '%s'\n",
419 options
.clear_forwardings
= 1;
420 options
.exit_on_forward_failure
= 1;
423 options
.log_level
= SYSLOG_LEVEL_QUIET
;
426 if (optarg
[0] == '^' && optarg
[2] == 0 &&
427 (u_char
) optarg
[1] >= 64 &&
428 (u_char
) optarg
[1] < 128)
429 options
.escape_char
= (u_char
) optarg
[1] & 31;
430 else if (strlen(optarg
) == 1)
431 options
.escape_char
= (u_char
) optarg
[0];
432 else if (strcmp(optarg
, "none") == 0)
433 options
.escape_char
= SSH_ESCAPECHAR_NONE
;
435 fprintf(stderr
, "Bad escape character '%s'.\n",
441 if (ciphers_valid(optarg
)) {
443 options
.ciphers
= xstrdup(optarg
);
444 options
.cipher
= SSH_CIPHER_INVALID
;
447 options
.cipher
= cipher_number(optarg
);
448 if (options
.cipher
== -1) {
450 "Unknown cipher type '%s'\n",
454 if (options
.cipher
== SSH_CIPHER_3DES
)
455 options
.ciphers
= "3des-cbc";
456 else if (options
.cipher
== SSH_CIPHER_BLOWFISH
)
457 options
.ciphers
= "blowfish-cbc";
459 options
.ciphers
= (char *)-1;
463 if (mac_valid(optarg
))
464 options
.macs
= xstrdup(optarg
);
466 fprintf(stderr
, "Unknown mac type '%s'\n",
472 if (options
.control_master
== SSHCTL_MASTER_YES
)
473 options
.control_master
= SSHCTL_MASTER_ASK
;
475 options
.control_master
= SSHCTL_MASTER_YES
;
478 options
.port
= a2port(optarg
);
479 if (options
.port
<= 0) {
480 fprintf(stderr
, "Bad port '%s'\n", optarg
);
485 options
.user
= optarg
;
489 if (parse_forward(&fwd
, optarg
, 0, 0))
490 add_local_forward(&options
, &fwd
);
493 "Bad local forwarding specification '%s'\n",
500 if (parse_forward(&fwd
, optarg
, 0, 1)) {
501 add_remote_forward(&options
, &fwd
);
504 "Bad remote forwarding specification "
511 if (parse_forward(&fwd
, optarg
, 1, 0)) {
512 add_local_forward(&options
, &fwd
);
515 "Bad dynamic forwarding specification "
522 options
.compression
= 1;
533 line
= xstrdup(optarg
);
534 if (process_config_line(&options
, host
? host
: "",
535 line
, "command-line", 0, &dummy
) != 0)
543 if (options
.control_path
!= NULL
)
544 free(options
.control_path
);
545 options
.control_path
= xstrdup(optarg
);
548 options
.bind_address
= optarg
;
561 if (ac
> 0 && !host
) {
562 if (strrchr(*av
, '@')) {
564 cp
= strrchr(p
, '@');
565 if (cp
== NULL
|| cp
== p
)
573 optind
= optreset
= 1;
579 /* Check that we got a host name. */
583 SSLeay_add_all_algorithms();
584 ERR_load_crypto_strings();
586 /* Initialize the command to execute on remote host. */
587 buffer_init(&command
);
590 * Save the command to execute on the remote host in a buffer. There
591 * is no limit on the length of the command, except by the maximum
592 * packet size. Also sets the tty flag if there is no command.
595 /* No command specified - execute shell on a tty. */
597 if (subsystem_flag
) {
599 "You must specify a subsystem to invoke.\n");
603 /* A command has been specified. Store it into the buffer. */
604 for (i
= 0; i
< ac
; i
++) {
606 buffer_append(&command
, " ", 1);
607 buffer_append(&command
, av
[i
], strlen(av
[i
]));
611 /* Cannot fork to background if no command. */
612 if (fork_after_authentication_flag
&& buffer_len(&command
) == 0 &&
614 fatal("Cannot fork into background without a command "
617 /* Allocate a tty by default if no command specified. */
618 if (buffer_len(&command
) == 0)
624 /* Do not allocate a tty if stdin is not a tty. */
625 if ((!isatty(fileno(stdin
)) || stdin_null_flag
) && !force_tty_flag
) {
627 logit("Pseudo-terminal will not be allocated because "
628 "stdin is not a terminal.");
633 * Initialize "log" output. Since we are the client all output
634 * actually goes to stderr.
637 options
.log_level
== -1 ? SYSLOG_LEVEL_INFO
: options
.log_level
,
638 SYSLOG_FACILITY_USER
, !use_syslog
);
641 * Read per-user configuration file. Ignore the system wide config
642 * file if the user specifies a config file on the command line.
644 if (config
!= NULL
) {
645 if (!read_config_file(config
, host
, &options
, 0))
646 fatal("Can't open user config file %.100s: "
647 "%.100s", config
, strerror(errno
));
649 r
= snprintf(buf
, sizeof buf
, "%s/%s", pw
->pw_dir
,
650 _PATH_SSH_USER_CONFFILE
);
651 if (r
> 0 && (size_t)r
< sizeof(buf
))
652 (void)read_config_file(buf
, host
, &options
, 1);
654 /* Read systemwide configuration file after use config. */
655 (void)read_config_file(_PATH_HOST_CONFIG_FILE
, host
,
659 /* Fill configuration defaults. */
660 fill_default_options(&options
);
662 channel_set_af(options
.address_family
);
665 log_init(argv0
, options
.log_level
, SYSLOG_FACILITY_USER
, !use_syslog
);
669 if (options
.user
== NULL
)
670 options
.user
= xstrdup(pw
->pw_name
);
672 /* Get default port if port has not been set. */
673 if (options
.port
== 0) {
674 sp
= getservbyname(SSH_SERVICE_NAME
, "tcp");
675 options
.port
= sp
? ntohs(sp
->s_port
) : SSH_DEFAULT_PORT
;
678 if (options
.local_command
!= NULL
) {
679 char thishost
[NI_MAXHOST
];
681 if (gethostname(thishost
, sizeof(thishost
)) == -1)
682 fatal("gethostname: %s", strerror(errno
));
683 snprintf(buf
, sizeof(buf
), "%d", options
.port
);
684 debug3("expanding LocalCommand: %s", options
.local_command
);
685 cp
= options
.local_command
;
686 options
.local_command
= percent_expand(cp
, "d", pw
->pw_dir
,
687 "h", options
.hostname
? options
.hostname
: host
,
688 "l", thishost
, "n", host
, "r", options
.user
, "p", buf
,
689 "u", pw
->pw_name
, (char *)NULL
);
690 debug3("expanded LocalCommand: %s", options
.local_command
);
694 if (options
.hostname
!= NULL
)
695 host
= options
.hostname
;
697 /* force lowercase for hostkey matching */
698 if (options
.host_key_alias
!= NULL
) {
699 for (p
= options
.host_key_alias
; *p
; p
++)
701 *p
= (char)tolower(*p
);
704 if (options
.proxy_command
!= NULL
&&
705 strcmp(options
.proxy_command
, "none") == 0) {
706 xfree(options
.proxy_command
);
707 options
.proxy_command
= NULL
;
709 if (options
.control_path
!= NULL
&&
710 strcmp(options
.control_path
, "none") == 0) {
711 xfree(options
.control_path
);
712 options
.control_path
= NULL
;
715 if (options
.control_path
!= NULL
) {
716 char thishost
[NI_MAXHOST
];
718 if (gethostname(thishost
, sizeof(thishost
)) == -1)
719 fatal("gethostname: %s", strerror(errno
));
720 snprintf(buf
, sizeof(buf
), "%d", options
.port
);
721 cp
= tilde_expand_filename(options
.control_path
,
723 xfree(options
.control_path
);
724 options
.control_path
= percent_expand(cp
, "p", buf
, "h", host
,
725 "r", options
.user
, "l", thishost
, (char *)NULL
);
728 if (muxclient_command
!= 0 && options
.control_path
== NULL
)
729 fatal("No ControlPath specified for \"-O\" command");
730 if (options
.control_path
!= NULL
)
731 muxclient(options
.control_path
);
733 timeout_ms
= options
.connection_timeout
* 1000;
735 /* Open a connection to the remote host. */
736 if (ssh_connect(host
, &hostaddr
, options
.port
,
737 options
.address_family
, options
.connection_attempts
, &timeout_ms
,
738 options
.tcp_keep_alive
,
740 options
.use_privileged_port
,
742 original_effective_uid
== 0 && options
.use_privileged_port
,
744 options
.proxy_command
) != 0)
748 debug3("timeout: %d ms remain after connect", timeout_ms
);
751 * If we successfully made the connection, load the host private key
752 * in case we will need it later for combined rsa-rhosts
753 * authentication. This must be done before releasing extra
754 * privileges, because the file is only readable by root.
755 * If we cannot access the private keys, load the public keys
756 * instead and try to execute the ssh-keysign helper instead.
758 sensitive_data
.nkeys
= 0;
759 sensitive_data
.keys
= NULL
;
760 sensitive_data
.external_keysign
= 0;
761 if (options
.rhosts_rsa_authentication
||
762 options
.hostbased_authentication
) {
763 sensitive_data
.nkeys
= 3;
764 sensitive_data
.keys
= xcalloc(sensitive_data
.nkeys
,
768 sensitive_data
.keys
[0] = key_load_private_type(KEY_RSA1
,
769 _PATH_HOST_KEY_FILE
, "", NULL
, NULL
);
770 sensitive_data
.keys
[1] = key_load_private_type(KEY_DSA
,
771 _PATH_HOST_DSA_KEY_FILE
, "", NULL
, NULL
);
772 sensitive_data
.keys
[2] = key_load_private_type(KEY_RSA
,
773 _PATH_HOST_RSA_KEY_FILE
, "", NULL
, NULL
);
776 if (options
.hostbased_authentication
== 1 &&
777 sensitive_data
.keys
[0] == NULL
&&
778 sensitive_data
.keys
[1] == NULL
&&
779 sensitive_data
.keys
[2] == NULL
) {
780 sensitive_data
.keys
[1] = key_load_public(
781 _PATH_HOST_DSA_KEY_FILE
, NULL
);
782 sensitive_data
.keys
[2] = key_load_public(
783 _PATH_HOST_RSA_KEY_FILE
, NULL
);
784 sensitive_data
.external_keysign
= 1;
788 * Get rid of any extra privileges that we may have. We will no
789 * longer need them. Also, extra privileges could make it very hard
790 * to read identity files and other non-world-readable files from the
791 * user's home directory if it happens to be on a NFS volume where
792 * root is mapped to nobody.
794 if (original_effective_uid
== 0) {
796 permanently_set_uid(pw
);
800 * Now that we are back to our own permissions, create ~/.ssh
801 * directory if it doesn't already exist.
803 r
= snprintf(buf
, sizeof buf
, "%s%s%s", pw
->pw_dir
,
804 strcmp(pw
->pw_dir
, "/") ? "/" : "", _PATH_SSH_USER_DIR
);
805 if (r
> 0 && (size_t)r
< sizeof(buf
) && stat(buf
, &st
) < 0)
806 if (mkdir(buf
, 0700) < 0)
807 error("Could not create directory '%.200s'.", buf
);
809 /* load options.identity_files */
810 load_public_identity_files();
812 /* Expand ~ in known host file names. */
814 options
.system_hostfile
=
815 tilde_expand_filename(options
.system_hostfile
, original_real_uid
);
816 options
.user_hostfile
=
817 tilde_expand_filename(options
.user_hostfile
, original_real_uid
);
818 options
.system_hostfile2
=
819 tilde_expand_filename(options
.system_hostfile2
, original_real_uid
);
820 options
.user_hostfile2
=
821 tilde_expand_filename(options
.user_hostfile2
, original_real_uid
);
823 signal(SIGPIPE
, SIG_IGN
); /* ignore SIGPIPE early */
825 /* Log into the remote system. Never returns if the login fails. */
826 ssh_login(&sensitive_data
, host
, (struct sockaddr
*)&hostaddr
,
829 /* We no longer need the private host keys. Clear them now. */
830 if (sensitive_data
.nkeys
!= 0) {
831 for (i
= 0; i
< sensitive_data
.nkeys
; i
++) {
832 if (sensitive_data
.keys
[i
] != NULL
) {
833 /* Destroys contents safely */
834 debug3("clear hostkey %d", i
);
835 key_free(sensitive_data
.keys
[i
]);
836 sensitive_data
.keys
[i
] = NULL
;
839 xfree(sensitive_data
.keys
);
841 for (i
= 0; i
< options
.num_identity_files
; i
++) {
842 if (options
.identity_files
[i
]) {
843 xfree(options
.identity_files
[i
]);
844 options
.identity_files
[i
] = NULL
;
846 if (options
.identity_keys
[i
]) {
847 key_free(options
.identity_keys
[i
]);
848 options
.identity_keys
[i
] = NULL
;
852 exit_status
= compat20
? ssh_session2() : ssh_session();
855 if (options
.control_path
!= NULL
&& muxserver_sock
!= -1)
856 unlink(options
.control_path
);
859 * Send SIGHUP to proxy command if used. We don't wait() in
860 * case it hangs and instead rely on init to reap the child
862 if (proxy_command_pid
> 1)
863 kill(proxy_command_pid
, SIGHUP
);
868 /* Callback for remote forward global requests */
870 ssh_confirm_remote_forward(int type
, u_int32_t seq
, void *ctxt
)
872 Forward
*rfwd
= (Forward
*)ctxt
;
874 /* XXX verbose() on failure? */
875 debug("remote forward %s for: listen %d, connect %s:%d",
876 type
== SSH2_MSG_REQUEST_SUCCESS
? "success" : "failure",
877 rfwd
->listen_port
, rfwd
->connect_host
, rfwd
->connect_port
);
878 if (type
== SSH2_MSG_REQUEST_SUCCESS
&& rfwd
->listen_port
== 0) {
879 logit("Allocated port %u for remote forward to %s:%d",
881 rfwd
->connect_host
, rfwd
->connect_port
);
884 if (type
== SSH2_MSG_REQUEST_FAILURE
) {
885 if (options
.exit_on_forward_failure
)
886 fatal("Error: remote port forwarding failed for "
887 "listen port %d", rfwd
->listen_port
);
889 logit("Warning: remote port forwarding failed for "
890 "listen port %d", rfwd
->listen_port
);
892 if (++remote_forward_confirms_received
== options
.num_remote_forwards
) {
893 debug("All remote forwarding requests processed");
894 if (fork_after_authentication_flag
) {
895 fork_after_authentication_flag
= 0;
896 if (daemon(1, 1) < 0)
897 fatal("daemon() failed: %.200s",
904 client_cleanup_stdio_fwd(int id
, void *arg
)
906 debug("stdio forwarding: done");
911 client_setup_stdio_fwd(const char *host_to_connect
, u_short port_to_connect
)
916 debug3("client_setup_stdio_fwd %s:%d", host_to_connect
,
919 in
= dup(STDIN_FILENO
);
920 out
= dup(STDOUT_FILENO
);
921 if (in
< 0 || out
< 0)
922 fatal("channel_connect_stdio_fwd: dup() in/out failed");
924 if ((c
= channel_connect_stdio_fwd(host_to_connect
, port_to_connect
,
927 channel_register_cleanup(c
->self
, client_cleanup_stdio_fwd
, 0);
932 ssh_init_forwarding(void)
937 if (stdio_forward_host
!= NULL
) {
939 fatal("stdio forwarding require Protocol 2");
941 if (!client_setup_stdio_fwd(stdio_forward_host
,
943 fatal("Failed to connect in stdio forward mode.");
946 /* Initiate local TCP/IP port forwardings. */
947 for (i
= 0; i
< options
.num_local_forwards
; i
++) {
948 debug("Local connections to %.200s:%d forwarded to remote "
950 (options
.local_forwards
[i
].listen_host
== NULL
) ?
951 (options
.gateway_ports
? "*" : "LOCALHOST") :
952 options
.local_forwards
[i
].listen_host
,
953 options
.local_forwards
[i
].listen_port
,
954 options
.local_forwards
[i
].connect_host
,
955 options
.local_forwards
[i
].connect_port
);
956 success
+= channel_setup_local_fwd_listener(
957 options
.local_forwards
[i
].listen_host
,
958 options
.local_forwards
[i
].listen_port
,
959 options
.local_forwards
[i
].connect_host
,
960 options
.local_forwards
[i
].connect_port
,
961 options
.gateway_ports
);
963 if (i
> 0 && success
!= i
&& options
.exit_on_forward_failure
)
964 fatal("Could not request local forwarding.");
965 if (i
> 0 && success
== 0)
966 error("Could not request local forwarding.");
968 /* Initiate remote TCP/IP port forwardings. */
969 for (i
= 0; i
< options
.num_remote_forwards
; i
++) {
970 debug("Remote connections from %.200s:%d forwarded to "
971 "local address %.200s:%d",
972 (options
.remote_forwards
[i
].listen_host
== NULL
) ?
973 "LOCALHOST" : options
.remote_forwards
[i
].listen_host
,
974 options
.remote_forwards
[i
].listen_port
,
975 options
.remote_forwards
[i
].connect_host
,
976 options
.remote_forwards
[i
].connect_port
);
977 if (channel_request_remote_forwarding(
978 options
.remote_forwards
[i
].listen_host
,
979 options
.remote_forwards
[i
].listen_port
,
980 options
.remote_forwards
[i
].connect_host
,
981 options
.remote_forwards
[i
].connect_port
) < 0) {
982 if (options
.exit_on_forward_failure
)
983 fatal("Could not request remote forwarding.");
985 logit("Warning: Could not request remote "
988 client_register_global_confirm(ssh_confirm_remote_forward
,
989 &options
.remote_forwards
[i
]);
992 /* Initiate tunnel forwarding. */
993 if (options
.tun_open
!= SSH_TUNMODE_NO
) {
994 if (client_request_tun_fwd(options
.tun_open
,
995 options
.tun_local
, options
.tun_remote
) == -1) {
996 if (options
.exit_on_forward_failure
)
997 fatal("Could not request tunnel forwarding.");
999 error("Could not request tunnel forwarding.");
1005 check_agent_present(void)
1007 if (options
.forward_agent
) {
1008 /* Clear agent forwarding if we don't have an agent. */
1009 if (!ssh_agent_present())
1010 options
.forward_agent
= 0;
1018 int interactive
= 0;
1022 const char *display
;
1024 /* Enable compression if requested. */
1025 if (options
.compression
) {
1026 debug("Requesting compression at level %d.",
1027 options
.compression_level
);
1029 if (options
.compression_level
< 1 ||
1030 options
.compression_level
> 9)
1031 fatal("Compression level must be from 1 (fast) to "
1034 /* Send the request. */
1035 packet_start(SSH_CMSG_REQUEST_COMPRESSION
);
1036 packet_put_int(options
.compression_level
);
1038 packet_write_wait();
1039 type
= packet_read();
1040 if (type
== SSH_SMSG_SUCCESS
)
1041 packet_start_compression(options
.compression_level
);
1042 else if (type
== SSH_SMSG_FAILURE
)
1043 logit("Warning: Remote host refused compression.");
1045 packet_disconnect("Protocol error waiting for "
1046 "compression response.");
1048 /* Allocate a pseudo tty if appropriate. */
1050 debug("Requesting pty.");
1052 /* Start the packet. */
1053 packet_start(SSH_CMSG_REQUEST_PTY
);
1055 /* Store TERM in the packet. There is no limit on the
1056 length of the string. */
1057 cp
= getenv("TERM");
1060 packet_put_cstring(cp
);
1062 /* Store window size in the packet. */
1063 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) < 0)
1064 memset(&ws
, 0, sizeof(ws
));
1065 packet_put_int((u_int
)ws
.ws_row
);
1066 packet_put_int((u_int
)ws
.ws_col
);
1067 packet_put_int((u_int
)ws
.ws_xpixel
);
1068 packet_put_int((u_int
)ws
.ws_ypixel
);
1070 /* Store tty modes in the packet. */
1071 tty_make_modes(fileno(stdin
), NULL
);
1073 /* Send the packet, and wait for it to leave. */
1075 packet_write_wait();
1077 /* Read response from the server. */
1078 type
= packet_read();
1079 if (type
== SSH_SMSG_SUCCESS
) {
1082 } else if (type
== SSH_SMSG_FAILURE
)
1083 logit("Warning: Remote host failed or refused to "
1084 "allocate a pseudo tty.");
1086 packet_disconnect("Protocol error waiting for pty "
1087 "request response.");
1089 /* Request X11 forwarding if enabled and DISPLAY is set. */
1090 display
= getenv("DISPLAY");
1091 if (options
.forward_x11
&& display
!= NULL
) {
1093 /* Get reasonable local authentication information. */
1094 client_x11_get_proto(display
, options
.xauth_location
,
1095 options
.forward_x11_trusted
, &proto
, &data
);
1096 /* Request forwarding with authentication spoofing. */
1097 debug("Requesting X11 forwarding with authentication "
1099 x11_request_forwarding_with_spoofing(0, display
, proto
, data
);
1101 /* Read response from the server. */
1102 type
= packet_read();
1103 if (type
== SSH_SMSG_SUCCESS
) {
1105 } else if (type
== SSH_SMSG_FAILURE
) {
1106 logit("Warning: Remote host denied X11 forwarding.");
1108 packet_disconnect("Protocol error waiting for X11 "
1112 /* Tell the packet module whether this is an interactive session. */
1113 packet_set_interactive(interactive
);
1115 /* Request authentication agent forwarding if appropriate. */
1116 check_agent_present();
1118 if (options
.forward_agent
) {
1119 debug("Requesting authentication agent forwarding.");
1120 auth_request_forwarding();
1122 /* Read response from the server. */
1123 type
= packet_read();
1125 if (type
!= SSH_SMSG_SUCCESS
)
1126 logit("Warning: Remote host denied authentication agent forwarding.");
1129 /* Initiate port forwardings. */
1130 ssh_init_forwarding();
1132 /* Execute a local command */
1133 if (options
.local_command
!= NULL
&&
1134 options
.permit_local_command
)
1135 ssh_local_cmd(options
.local_command
);
1138 * If requested and we are not interested in replies to remote
1139 * forwarding requests, then let ssh continue in the background.
1141 if (fork_after_authentication_flag
&&
1142 (!options
.exit_on_forward_failure
||
1143 options
.num_remote_forwards
== 0)) {
1144 fork_after_authentication_flag
= 0;
1145 if (daemon(1, 1) < 0)
1146 fatal("daemon() failed: %.200s", strerror(errno
));
1150 * If a command was specified on the command line, execute the
1151 * command now. Otherwise request the server to start a shell.
1153 if (buffer_len(&command
) > 0) {
1154 int len
= buffer_len(&command
);
1157 debug("Sending command: %.*s", len
,
1158 (u_char
*)buffer_ptr(&command
));
1159 packet_start(SSH_CMSG_EXEC_CMD
);
1160 packet_put_string(buffer_ptr(&command
), buffer_len(&command
));
1162 packet_write_wait();
1164 debug("Requesting shell.");
1165 packet_start(SSH_CMSG_EXEC_SHELL
);
1167 packet_write_wait();
1170 /* Enter the interactive session. */
1171 return client_loop(have_tty
, tty_flag
?
1172 options
.escape_char
: SSH_ESCAPECHAR_NONE
, 0);
1175 /* request pty/x11/agent/tcpfwd/shell for channel */
1177 ssh_session2_setup(int id
, void *arg
)
1179 extern char **environ
;
1180 const char *display
;
1181 int interactive
= tty_flag
;
1183 display
= getenv("DISPLAY");
1184 if (options
.forward_x11
&& display
!= NULL
) {
1186 /* Get reasonable local authentication information. */
1187 client_x11_get_proto(display
, options
.xauth_location
,
1188 options
.forward_x11_trusted
, &proto
, &data
);
1189 /* Request forwarding with authentication spoofing. */
1190 debug("Requesting X11 forwarding with authentication "
1192 x11_request_forwarding_with_spoofing(id
, display
, proto
, data
);
1194 /* XXX wait for reply */
1197 check_agent_present();
1198 if (options
.forward_agent
) {
1199 debug("Requesting authentication agent forwarding.");
1200 channel_request_start(id
, "auth-agent-req@openssh.com", 0);
1204 client_session2_setup(id
, tty_flag
, subsystem_flag
, getenv("TERM"),
1205 NULL
, fileno(stdin
), &command
, environ
);
1207 packet_set_interactive(interactive
);
1210 /* open new channel for a session */
1212 ssh_session2_open(void)
1215 int window
, packetmax
, in
, out
, err
;
1217 if (stdin_null_flag
) {
1218 in
= open(_PATH_DEVNULL
, O_RDONLY
);
1220 in
= dup(STDIN_FILENO
);
1222 out
= dup(STDOUT_FILENO
);
1223 err
= dup(STDERR_FILENO
);
1225 if (in
< 0 || out
< 0 || err
< 0)
1226 fatal("dup() in/out/err failed");
1228 /* enable nonblocking unless tty */
1236 window
= CHAN_SES_WINDOW_DEFAULT
;
1237 packetmax
= CHAN_SES_PACKET_DEFAULT
;
1243 "session", SSH_CHANNEL_OPENING
, in
, out
, err
,
1244 window
, packetmax
, CHAN_EXTENDED_WRITE
,
1245 "client-session", /*nonblock*/0);
1247 debug3("ssh_session2_open: channel_new: %d", c
->self
);
1249 channel_send_open(c
->self
);
1251 channel_register_open_confirm(c
->self
,
1252 ssh_session2_setup
, NULL
);
1262 /* XXX should be pre-session */
1263 ssh_init_forwarding();
1265 if (!no_shell_flag
|| (datafellows
& SSH_BUG_DUMMYCHAN
))
1266 id
= ssh_session2_open();
1268 /* If we don't expect to open a new session, then disallow it */
1269 if (options
.control_master
== SSHCTL_MASTER_NO
&&
1270 (datafellows
& SSH_NEW_OPENSSH
)) {
1271 debug("Requesting no-more-sessions@openssh.com");
1272 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
1273 packet_put_cstring("no-more-sessions@openssh.com");
1278 /* Execute a local command */
1279 if (options
.local_command
!= NULL
&&
1280 options
.permit_local_command
)
1281 ssh_local_cmd(options
.local_command
);
1283 /* Start listening for multiplex clients */
1286 /* If requested, let ssh continue in the background. */
1287 if (fork_after_authentication_flag
) {
1288 fork_after_authentication_flag
= 0;
1289 if (daemon(1, 1) < 0)
1290 fatal("daemon() failed: %.200s", strerror(errno
));
1293 if (options
.use_roaming
)
1296 return client_loop(tty_flag
, tty_flag
?
1297 options
.escape_char
: SSH_ESCAPECHAR_NONE
, id
);
1301 load_public_identity_files(void)
1303 char *filename
, *cp
, thishost
[NI_MAXHOST
];
1304 char *pwdir
= NULL
, *pwname
= NULL
;
1311 if (options
.smartcard_device
!= NULL
&&
1312 options
.num_identity_files
< SSH_MAX_IDENTITY_FILES
&&
1313 (keys
= sc_get_keys(options
.smartcard_device
, NULL
)) != NULL
) {
1315 for (i
= 0; keys
[i
] != NULL
; i
++) {
1317 memmove(&options
.identity_files
[1],
1318 &options
.identity_files
[0],
1319 sizeof(char *) * (SSH_MAX_IDENTITY_FILES
- 1));
1320 memmove(&options
.identity_keys
[1],
1321 &options
.identity_keys
[0],
1322 sizeof(Key
*) * (SSH_MAX_IDENTITY_FILES
- 1));
1323 options
.num_identity_files
++;
1324 options
.identity_keys
[0] = keys
[i
];
1325 options
.identity_files
[0] = sc_get_key_label(keys
[i
]);
1327 if (options
.num_identity_files
> SSH_MAX_IDENTITY_FILES
)
1328 options
.num_identity_files
= SSH_MAX_IDENTITY_FILES
;
1332 #endif /* SMARTCARD */
1333 if ((pw
= getpwuid(original_real_uid
)) == NULL
)
1334 fatal("load_public_identity_files: getpwuid failed");
1335 pwname
= xstrdup(pw
->pw_name
);
1336 pwdir
= xstrdup(pw
->pw_dir
);
1337 if (gethostname(thishost
, sizeof(thishost
)) == -1)
1338 fatal("load_public_identity_files: gethostname: %s",
1340 for (; i
< options
.num_identity_files
; i
++) {
1341 cp
= tilde_expand_filename(options
.identity_files
[i
],
1343 filename
= percent_expand(cp
, "d", pwdir
,
1344 "u", pwname
, "l", thishost
, "h", host
,
1345 "r", options
.user
, (char *)NULL
);
1347 public = key_load_public(filename
, NULL
);
1348 debug("identity file %s type %d", filename
,
1349 public ? public->type
: -1);
1350 xfree(options
.identity_files
[i
]);
1351 options
.identity_files
[i
] = filename
;
1352 options
.identity_keys
[i
] = public;
1354 bzero(pwname
, strlen(pwname
));
1356 bzero(pwdir
, strlen(pwdir
));