1 /* $OpenBSD: ssh.c,v 1.335 2010/02/26 20:29:54 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"
107 #include "ssh-pkcs11.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 pkcs11] [-i identity_file]\n"
191 " [-L [bind_address:]port:host:hostport]\n"
192 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
193 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
194 " [-W host:port] [-w local_tun[:remote_tun]]\n"
195 " [user@]hostname [command]\n"
200 static int ssh_session(void);
201 static int ssh_session2(void);
202 static void load_public_identity_files(void);
204 /* from muxclient.c */
205 void muxclient(const char *);
206 void muxserver_listen(void);
209 * Main program for the ssh client.
212 main(int ac
, char **av
)
214 int i
, r
, opt
, exit_status
, use_syslog
;
215 char *p
, *cp
, *line
, *argv0
, buf
[MAXPATHLEN
];
218 int dummy
, timeout_ms
;
219 extern int optind
, optreset
;
224 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
227 __progname
= ssh_get_progname(av
[0]);
231 * Save the original real uid. It will be needed later (uid-swapping
232 * may clobber the real uid).
234 original_real_uid
= getuid();
235 original_effective_uid
= geteuid();
238 * Use uid-swapping to give up root privileges for the duration of
239 * option processing. We will re-instantiate the rights when we are
240 * ready to create the privileged port, and will permanently drop
241 * them when the port has been created (actually, when the connection
242 * has been made, as we may need to create the port several times).
246 #ifdef HAVE_SETRLIMIT
247 /* If we are installed setuid root be careful to not drop core. */
248 if (original_real_uid
!= original_effective_uid
) {
250 rlim
.rlim_cur
= rlim
.rlim_max
= 0;
251 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
252 fatal("setrlimit failed: %.100s", strerror(errno
));
256 pw
= getpwuid(original_real_uid
);
258 logit("You don't exist, go away!");
261 /* Take a copy of the returned structure. */
265 * Set our umask to something reasonable, as some files are created
266 * with the default umask. This will make them world-readable but
267 * writable only by the owner, which is ok for all files for which we
268 * don't set the modes explicitly.
273 * Initialize option structure to indicate that no values have been
276 initialize_options(&options
);
278 /* Parse command-line arguments. */
284 while ((opt
= getopt(ac
, av
, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
285 "ACD:F:I:KL:MNO:PR:S:TVw:W:XYy")) != -1) {
288 options
.protocol
= SSH_PROTO_1
;
291 options
.protocol
= SSH_PROTO_2
;
294 options
.address_family
= AF_INET
;
297 options
.address_family
= AF_INET6
;
303 fork_after_authentication_flag
= 1;
307 options
.forward_x11
= 0;
310 options
.forward_x11
= 1;
316 options
.forward_x11
= 1;
317 options
.forward_x11_trusted
= 1;
320 options
.gateway_ports
= 1;
323 if (stdio_forward_host
!= NULL
)
324 fatal("Cannot specify multiplexing "
326 else if (muxclient_command
!= 0)
327 fatal("Multiplexing command already specified");
328 if (strcmp(optarg
, "check") == 0)
329 muxclient_command
= SSHMUX_COMMAND_ALIVE_CHECK
;
330 else if (strcmp(optarg
, "exit") == 0)
331 muxclient_command
= SSHMUX_COMMAND_TERMINATE
;
333 fatal("Invalid multiplex command.");
335 case 'P': /* deprecated */
336 options
.use_privileged_port
= 0;
339 options
.forward_agent
= 0;
342 options
.forward_agent
= 1;
345 options
.gss_deleg_creds
= 0;
348 options
.gss_authentication
= 1;
349 options
.gss_deleg_creds
= 1;
352 if (stat(optarg
, &st
) < 0) {
353 fprintf(stderr
, "Warning: Identity file %s "
354 "not accessible: %s.\n", optarg
,
358 if (options
.num_identity_files
>=
359 SSH_MAX_IDENTITY_FILES
)
360 fatal("Too many identity files specified "
361 "(max %d)", SSH_MAX_IDENTITY_FILES
);
362 options
.identity_files
[options
.num_identity_files
++] =
367 options
.pkcs11_provider
= xstrdup(optarg
);
369 fprintf(stderr
, "no support for PKCS#11.\n");
378 if (debug_flag
== 0) {
380 options
.log_level
= SYSLOG_LEVEL_DEBUG1
;
382 if (options
.log_level
< SYSLOG_LEVEL_DEBUG3
)
388 fprintf(stderr
, "%s, %s\n",
389 SSH_RELEASE
, SSLeay_version(SSLEAY_VERSION
));
394 if (options
.tun_open
== -1)
395 options
.tun_open
= SSH_TUNMODE_DEFAULT
;
396 options
.tun_local
= a2tun(optarg
, &options
.tun_remote
);
397 if (options
.tun_local
== SSH_TUNID_ERR
) {
399 "Bad tun device '%s'\n", optarg
);
404 if (stdio_forward_host
!= NULL
)
405 fatal("stdio forward already specified");
406 if (muxclient_command
!= 0)
407 fatal("Cannot specify stdio forward with -O");
408 if (parse_forward(&fwd
, optarg
, 1, 0)) {
409 stdio_forward_host
= fwd
.listen_host
;
410 stdio_forward_port
= fwd
.listen_port
;
411 xfree(fwd
.connect_host
);
414 "Bad stdio forwarding specification '%s'\n",
420 options
.clear_forwardings
= 1;
421 options
.exit_on_forward_failure
= 1;
424 options
.log_level
= SYSLOG_LEVEL_QUIET
;
427 if (optarg
[0] == '^' && optarg
[2] == 0 &&
428 (u_char
) optarg
[1] >= 64 &&
429 (u_char
) optarg
[1] < 128)
430 options
.escape_char
= (u_char
) optarg
[1] & 31;
431 else if (strlen(optarg
) == 1)
432 options
.escape_char
= (u_char
) optarg
[0];
433 else if (strcmp(optarg
, "none") == 0)
434 options
.escape_char
= SSH_ESCAPECHAR_NONE
;
436 fprintf(stderr
, "Bad escape character '%s'.\n",
442 if (ciphers_valid(optarg
)) {
444 options
.ciphers
= xstrdup(optarg
);
445 options
.cipher
= SSH_CIPHER_INVALID
;
448 options
.cipher
= cipher_number(optarg
);
449 if (options
.cipher
== -1) {
451 "Unknown cipher type '%s'\n",
455 if (options
.cipher
== SSH_CIPHER_3DES
)
456 options
.ciphers
= "3des-cbc";
457 else if (options
.cipher
== SSH_CIPHER_BLOWFISH
)
458 options
.ciphers
= "blowfish-cbc";
460 options
.ciphers
= (char *)-1;
464 if (mac_valid(optarg
))
465 options
.macs
= xstrdup(optarg
);
467 fprintf(stderr
, "Unknown mac type '%s'\n",
473 if (options
.control_master
== SSHCTL_MASTER_YES
)
474 options
.control_master
= SSHCTL_MASTER_ASK
;
476 options
.control_master
= SSHCTL_MASTER_YES
;
479 options
.port
= a2port(optarg
);
480 if (options
.port
<= 0) {
481 fprintf(stderr
, "Bad port '%s'\n", optarg
);
486 options
.user
= optarg
;
490 if (parse_forward(&fwd
, optarg
, 0, 0))
491 add_local_forward(&options
, &fwd
);
494 "Bad local forwarding specification '%s'\n",
501 if (parse_forward(&fwd
, optarg
, 0, 1)) {
502 add_remote_forward(&options
, &fwd
);
505 "Bad remote forwarding specification "
512 if (parse_forward(&fwd
, optarg
, 1, 0)) {
513 add_local_forward(&options
, &fwd
);
516 "Bad dynamic forwarding specification "
523 options
.compression
= 1;
534 line
= xstrdup(optarg
);
535 if (process_config_line(&options
, host
? host
: "",
536 line
, "command-line", 0, &dummy
) != 0)
544 if (options
.control_path
!= NULL
)
545 free(options
.control_path
);
546 options
.control_path
= xstrdup(optarg
);
549 options
.bind_address
= optarg
;
562 if (ac
> 0 && !host
) {
563 if (strrchr(*av
, '@')) {
565 cp
= strrchr(p
, '@');
566 if (cp
== NULL
|| cp
== p
)
574 optind
= optreset
= 1;
580 /* Check that we got a host name. */
584 SSLeay_add_all_algorithms();
585 ERR_load_crypto_strings();
587 /* Initialize the command to execute on remote host. */
588 buffer_init(&command
);
591 * Save the command to execute on the remote host in a buffer. There
592 * is no limit on the length of the command, except by the maximum
593 * packet size. Also sets the tty flag if there is no command.
596 /* No command specified - execute shell on a tty. */
598 if (subsystem_flag
) {
600 "You must specify a subsystem to invoke.\n");
604 /* A command has been specified. Store it into the buffer. */
605 for (i
= 0; i
< ac
; i
++) {
607 buffer_append(&command
, " ", 1);
608 buffer_append(&command
, av
[i
], strlen(av
[i
]));
612 /* Cannot fork to background if no command. */
613 if (fork_after_authentication_flag
&& buffer_len(&command
) == 0 &&
615 fatal("Cannot fork into background without a command "
618 /* Allocate a tty by default if no command specified. */
619 if (buffer_len(&command
) == 0)
625 /* Do not allocate a tty if stdin is not a tty. */
626 if ((!isatty(fileno(stdin
)) || stdin_null_flag
) && !force_tty_flag
) {
628 logit("Pseudo-terminal will not be allocated because "
629 "stdin is not a terminal.");
634 * Initialize "log" output. Since we are the client all output
635 * actually goes to stderr.
638 options
.log_level
== -1 ? SYSLOG_LEVEL_INFO
: options
.log_level
,
639 SYSLOG_FACILITY_USER
, !use_syslog
);
642 * Read per-user configuration file. Ignore the system wide config
643 * file if the user specifies a config file on the command line.
645 if (config
!= NULL
) {
646 if (!read_config_file(config
, host
, &options
, 0))
647 fatal("Can't open user config file %.100s: "
648 "%.100s", config
, strerror(errno
));
650 r
= snprintf(buf
, sizeof buf
, "%s/%s", pw
->pw_dir
,
651 _PATH_SSH_USER_CONFFILE
);
652 if (r
> 0 && (size_t)r
< sizeof(buf
))
653 (void)read_config_file(buf
, host
, &options
, 1);
655 /* Read systemwide configuration file after use config. */
656 (void)read_config_file(_PATH_HOST_CONFIG_FILE
, host
,
660 /* Fill configuration defaults. */
661 fill_default_options(&options
);
663 channel_set_af(options
.address_family
);
666 log_init(argv0
, options
.log_level
, SYSLOG_FACILITY_USER
, !use_syslog
);
670 if (options
.user
== NULL
)
671 options
.user
= xstrdup(pw
->pw_name
);
673 /* Get default port if port has not been set. */
674 if (options
.port
== 0) {
675 sp
= getservbyname(SSH_SERVICE_NAME
, "tcp");
676 options
.port
= sp
? ntohs(sp
->s_port
) : SSH_DEFAULT_PORT
;
679 if (options
.local_command
!= NULL
) {
680 char thishost
[NI_MAXHOST
];
682 if (gethostname(thishost
, sizeof(thishost
)) == -1)
683 fatal("gethostname: %s", strerror(errno
));
684 snprintf(buf
, sizeof(buf
), "%d", options
.port
);
685 debug3("expanding LocalCommand: %s", options
.local_command
);
686 cp
= options
.local_command
;
687 options
.local_command
= percent_expand(cp
, "d", pw
->pw_dir
,
688 "h", options
.hostname
? options
.hostname
: host
,
689 "l", thishost
, "n", host
, "r", options
.user
, "p", buf
,
690 "u", pw
->pw_name
, (char *)NULL
);
691 debug3("expanded LocalCommand: %s", options
.local_command
);
695 if (options
.hostname
!= NULL
)
696 host
= options
.hostname
;
698 /* force lowercase for hostkey matching */
699 if (options
.host_key_alias
!= NULL
) {
700 for (p
= options
.host_key_alias
; *p
; p
++)
702 *p
= (char)tolower(*p
);
705 if (options
.proxy_command
!= NULL
&&
706 strcmp(options
.proxy_command
, "none") == 0) {
707 xfree(options
.proxy_command
);
708 options
.proxy_command
= NULL
;
710 if (options
.control_path
!= NULL
&&
711 strcmp(options
.control_path
, "none") == 0) {
712 xfree(options
.control_path
);
713 options
.control_path
= NULL
;
716 if (options
.control_path
!= NULL
) {
717 char thishost
[NI_MAXHOST
];
719 if (gethostname(thishost
, sizeof(thishost
)) == -1)
720 fatal("gethostname: %s", strerror(errno
));
721 snprintf(buf
, sizeof(buf
), "%d", options
.port
);
722 cp
= tilde_expand_filename(options
.control_path
,
724 xfree(options
.control_path
);
725 options
.control_path
= percent_expand(cp
, "p", buf
, "h", host
,
726 "r", options
.user
, "l", thishost
, (char *)NULL
);
729 if (muxclient_command
!= 0 && options
.control_path
== NULL
)
730 fatal("No ControlPath specified for \"-O\" command");
731 if (options
.control_path
!= NULL
)
732 muxclient(options
.control_path
);
734 timeout_ms
= options
.connection_timeout
* 1000;
736 /* Open a connection to the remote host. */
737 if (ssh_connect(host
, &hostaddr
, options
.port
,
738 options
.address_family
, options
.connection_attempts
, &timeout_ms
,
739 options
.tcp_keep_alive
,
741 options
.use_privileged_port
,
743 original_effective_uid
== 0 && options
.use_privileged_port
,
745 options
.proxy_command
) != 0)
749 debug3("timeout: %d ms remain after connect", timeout_ms
);
752 * If we successfully made the connection, load the host private key
753 * in case we will need it later for combined rsa-rhosts
754 * authentication. This must be done before releasing extra
755 * privileges, because the file is only readable by root.
756 * If we cannot access the private keys, load the public keys
757 * instead and try to execute the ssh-keysign helper instead.
759 sensitive_data
.nkeys
= 0;
760 sensitive_data
.keys
= NULL
;
761 sensitive_data
.external_keysign
= 0;
762 if (options
.rhosts_rsa_authentication
||
763 options
.hostbased_authentication
) {
764 sensitive_data
.nkeys
= 3;
765 sensitive_data
.keys
= xcalloc(sensitive_data
.nkeys
,
769 sensitive_data
.keys
[0] = key_load_private_type(KEY_RSA1
,
770 _PATH_HOST_KEY_FILE
, "", NULL
, NULL
);
771 sensitive_data
.keys
[1] = key_load_private_type(KEY_DSA
,
772 _PATH_HOST_DSA_KEY_FILE
, "", NULL
, NULL
);
773 sensitive_data
.keys
[2] = key_load_private_type(KEY_RSA
,
774 _PATH_HOST_RSA_KEY_FILE
, "", NULL
, NULL
);
777 if (options
.hostbased_authentication
== 1 &&
778 sensitive_data
.keys
[0] == NULL
&&
779 sensitive_data
.keys
[1] == NULL
&&
780 sensitive_data
.keys
[2] == NULL
) {
781 sensitive_data
.keys
[1] = key_load_public(
782 _PATH_HOST_DSA_KEY_FILE
, NULL
);
783 sensitive_data
.keys
[2] = key_load_public(
784 _PATH_HOST_RSA_KEY_FILE
, NULL
);
785 sensitive_data
.external_keysign
= 1;
789 * Get rid of any extra privileges that we may have. We will no
790 * longer need them. Also, extra privileges could make it very hard
791 * to read identity files and other non-world-readable files from the
792 * user's home directory if it happens to be on a NFS volume where
793 * root is mapped to nobody.
795 if (original_effective_uid
== 0) {
797 permanently_set_uid(pw
);
801 * Now that we are back to our own permissions, create ~/.ssh
802 * directory if it doesn't already exist.
804 r
= snprintf(buf
, sizeof buf
, "%s%s%s", pw
->pw_dir
,
805 strcmp(pw
->pw_dir
, "/") ? "/" : "", _PATH_SSH_USER_DIR
);
806 if (r
> 0 && (size_t)r
< sizeof(buf
) && stat(buf
, &st
) < 0)
807 if (mkdir(buf
, 0700) < 0)
808 error("Could not create directory '%.200s'.", buf
);
810 /* load options.identity_files */
811 load_public_identity_files();
813 /* Expand ~ in known host file names. */
815 options
.system_hostfile
=
816 tilde_expand_filename(options
.system_hostfile
, original_real_uid
);
817 options
.user_hostfile
=
818 tilde_expand_filename(options
.user_hostfile
, original_real_uid
);
819 options
.system_hostfile2
=
820 tilde_expand_filename(options
.system_hostfile2
, original_real_uid
);
821 options
.user_hostfile2
=
822 tilde_expand_filename(options
.user_hostfile2
, original_real_uid
);
824 signal(SIGPIPE
, SIG_IGN
); /* ignore SIGPIPE early */
826 /* Log into the remote system. Never returns if the login fails. */
827 ssh_login(&sensitive_data
, host
, (struct sockaddr
*)&hostaddr
,
830 /* We no longer need the private host keys. Clear them now. */
831 if (sensitive_data
.nkeys
!= 0) {
832 for (i
= 0; i
< sensitive_data
.nkeys
; i
++) {
833 if (sensitive_data
.keys
[i
] != NULL
) {
834 /* Destroys contents safely */
835 debug3("clear hostkey %d", i
);
836 key_free(sensitive_data
.keys
[i
]);
837 sensitive_data
.keys
[i
] = NULL
;
840 xfree(sensitive_data
.keys
);
842 for (i
= 0; i
< options
.num_identity_files
; i
++) {
843 if (options
.identity_files
[i
]) {
844 xfree(options
.identity_files
[i
]);
845 options
.identity_files
[i
] = NULL
;
847 if (options
.identity_keys
[i
]) {
848 key_free(options
.identity_keys
[i
]);
849 options
.identity_keys
[i
] = NULL
;
853 exit_status
= compat20
? ssh_session2() : ssh_session();
856 if (options
.control_path
!= NULL
&& muxserver_sock
!= -1)
857 unlink(options
.control_path
);
860 * Send SIGHUP to proxy command if used. We don't wait() in
861 * case it hangs and instead rely on init to reap the child
863 if (proxy_command_pid
> 1)
864 kill(proxy_command_pid
, SIGHUP
);
869 /* Callback for remote forward global requests */
871 ssh_confirm_remote_forward(int type
, u_int32_t seq
, void *ctxt
)
873 Forward
*rfwd
= (Forward
*)ctxt
;
875 /* XXX verbose() on failure? */
876 debug("remote forward %s for: listen %d, connect %s:%d",
877 type
== SSH2_MSG_REQUEST_SUCCESS
? "success" : "failure",
878 rfwd
->listen_port
, rfwd
->connect_host
, rfwd
->connect_port
);
879 if (type
== SSH2_MSG_REQUEST_SUCCESS
&& rfwd
->listen_port
== 0) {
880 logit("Allocated port %u for remote forward to %s:%d",
882 rfwd
->connect_host
, rfwd
->connect_port
);
885 if (type
== SSH2_MSG_REQUEST_FAILURE
) {
886 if (options
.exit_on_forward_failure
)
887 fatal("Error: remote port forwarding failed for "
888 "listen port %d", rfwd
->listen_port
);
890 logit("Warning: remote port forwarding failed for "
891 "listen port %d", rfwd
->listen_port
);
893 if (++remote_forward_confirms_received
== options
.num_remote_forwards
) {
894 debug("All remote forwarding requests processed");
895 if (fork_after_authentication_flag
) {
896 fork_after_authentication_flag
= 0;
897 if (daemon(1, 1) < 0)
898 fatal("daemon() failed: %.200s",
905 client_cleanup_stdio_fwd(int id
, void *arg
)
907 debug("stdio forwarding: done");
912 client_setup_stdio_fwd(const char *host_to_connect
, u_short port_to_connect
)
917 debug3("client_setup_stdio_fwd %s:%d", host_to_connect
,
920 in
= dup(STDIN_FILENO
);
921 out
= dup(STDOUT_FILENO
);
922 if (in
< 0 || out
< 0)
923 fatal("channel_connect_stdio_fwd: dup() in/out failed");
925 if ((c
= channel_connect_stdio_fwd(host_to_connect
, port_to_connect
,
928 channel_register_cleanup(c
->self
, client_cleanup_stdio_fwd
, 0);
933 ssh_init_forwarding(void)
938 if (stdio_forward_host
!= NULL
) {
940 fatal("stdio forwarding require Protocol 2");
942 if (!client_setup_stdio_fwd(stdio_forward_host
,
944 fatal("Failed to connect in stdio forward mode.");
947 /* Initiate local TCP/IP port forwardings. */
948 for (i
= 0; i
< options
.num_local_forwards
; i
++) {
949 debug("Local connections to %.200s:%d forwarded to remote "
951 (options
.local_forwards
[i
].listen_host
== NULL
) ?
952 (options
.gateway_ports
? "*" : "LOCALHOST") :
953 options
.local_forwards
[i
].listen_host
,
954 options
.local_forwards
[i
].listen_port
,
955 options
.local_forwards
[i
].connect_host
,
956 options
.local_forwards
[i
].connect_port
);
957 success
+= channel_setup_local_fwd_listener(
958 options
.local_forwards
[i
].listen_host
,
959 options
.local_forwards
[i
].listen_port
,
960 options
.local_forwards
[i
].connect_host
,
961 options
.local_forwards
[i
].connect_port
,
962 options
.gateway_ports
);
964 if (i
> 0 && success
!= i
&& options
.exit_on_forward_failure
)
965 fatal("Could not request local forwarding.");
966 if (i
> 0 && success
== 0)
967 error("Could not request local forwarding.");
969 /* Initiate remote TCP/IP port forwardings. */
970 for (i
= 0; i
< options
.num_remote_forwards
; i
++) {
971 debug("Remote connections from %.200s:%d forwarded to "
972 "local address %.200s:%d",
973 (options
.remote_forwards
[i
].listen_host
== NULL
) ?
974 "LOCALHOST" : options
.remote_forwards
[i
].listen_host
,
975 options
.remote_forwards
[i
].listen_port
,
976 options
.remote_forwards
[i
].connect_host
,
977 options
.remote_forwards
[i
].connect_port
);
978 if (channel_request_remote_forwarding(
979 options
.remote_forwards
[i
].listen_host
,
980 options
.remote_forwards
[i
].listen_port
,
981 options
.remote_forwards
[i
].connect_host
,
982 options
.remote_forwards
[i
].connect_port
) < 0) {
983 if (options
.exit_on_forward_failure
)
984 fatal("Could not request remote forwarding.");
986 logit("Warning: Could not request remote "
989 client_register_global_confirm(ssh_confirm_remote_forward
,
990 &options
.remote_forwards
[i
]);
993 /* Initiate tunnel forwarding. */
994 if (options
.tun_open
!= SSH_TUNMODE_NO
) {
995 if (client_request_tun_fwd(options
.tun_open
,
996 options
.tun_local
, options
.tun_remote
) == -1) {
997 if (options
.exit_on_forward_failure
)
998 fatal("Could not request tunnel forwarding.");
1000 error("Could not request tunnel forwarding.");
1006 check_agent_present(void)
1008 if (options
.forward_agent
) {
1009 /* Clear agent forwarding if we don't have an agent. */
1010 if (!ssh_agent_present())
1011 options
.forward_agent
= 0;
1019 int interactive
= 0;
1023 const char *display
;
1025 /* Enable compression if requested. */
1026 if (options
.compression
) {
1027 debug("Requesting compression at level %d.",
1028 options
.compression_level
);
1030 if (options
.compression_level
< 1 ||
1031 options
.compression_level
> 9)
1032 fatal("Compression level must be from 1 (fast) to "
1035 /* Send the request. */
1036 packet_start(SSH_CMSG_REQUEST_COMPRESSION
);
1037 packet_put_int(options
.compression_level
);
1039 packet_write_wait();
1040 type
= packet_read();
1041 if (type
== SSH_SMSG_SUCCESS
)
1042 packet_start_compression(options
.compression_level
);
1043 else if (type
== SSH_SMSG_FAILURE
)
1044 logit("Warning: Remote host refused compression.");
1046 packet_disconnect("Protocol error waiting for "
1047 "compression response.");
1049 /* Allocate a pseudo tty if appropriate. */
1051 debug("Requesting pty.");
1053 /* Start the packet. */
1054 packet_start(SSH_CMSG_REQUEST_PTY
);
1056 /* Store TERM in the packet. There is no limit on the
1057 length of the string. */
1058 cp
= getenv("TERM");
1061 packet_put_cstring(cp
);
1063 /* Store window size in the packet. */
1064 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) < 0)
1065 memset(&ws
, 0, sizeof(ws
));
1066 packet_put_int((u_int
)ws
.ws_row
);
1067 packet_put_int((u_int
)ws
.ws_col
);
1068 packet_put_int((u_int
)ws
.ws_xpixel
);
1069 packet_put_int((u_int
)ws
.ws_ypixel
);
1071 /* Store tty modes in the packet. */
1072 tty_make_modes(fileno(stdin
), NULL
);
1074 /* Send the packet, and wait for it to leave. */
1076 packet_write_wait();
1078 /* Read response from the server. */
1079 type
= packet_read();
1080 if (type
== SSH_SMSG_SUCCESS
) {
1083 } else if (type
== SSH_SMSG_FAILURE
)
1084 logit("Warning: Remote host failed or refused to "
1085 "allocate a pseudo tty.");
1087 packet_disconnect("Protocol error waiting for pty "
1088 "request response.");
1090 /* Request X11 forwarding if enabled and DISPLAY is set. */
1091 display
= getenv("DISPLAY");
1092 if (options
.forward_x11
&& display
!= NULL
) {
1094 /* Get reasonable local authentication information. */
1095 client_x11_get_proto(display
, options
.xauth_location
,
1096 options
.forward_x11_trusted
, &proto
, &data
);
1097 /* Request forwarding with authentication spoofing. */
1098 debug("Requesting X11 forwarding with authentication "
1100 x11_request_forwarding_with_spoofing(0, display
, proto
, data
);
1102 /* Read response from the server. */
1103 type
= packet_read();
1104 if (type
== SSH_SMSG_SUCCESS
) {
1106 } else if (type
== SSH_SMSG_FAILURE
) {
1107 logit("Warning: Remote host denied X11 forwarding.");
1109 packet_disconnect("Protocol error waiting for X11 "
1113 /* Tell the packet module whether this is an interactive session. */
1114 packet_set_interactive(interactive
);
1116 /* Request authentication agent forwarding if appropriate. */
1117 check_agent_present();
1119 if (options
.forward_agent
) {
1120 debug("Requesting authentication agent forwarding.");
1121 auth_request_forwarding();
1123 /* Read response from the server. */
1124 type
= packet_read();
1126 if (type
!= SSH_SMSG_SUCCESS
)
1127 logit("Warning: Remote host denied authentication agent forwarding.");
1130 /* Initiate port forwardings. */
1131 ssh_init_forwarding();
1133 /* Execute a local command */
1134 if (options
.local_command
!= NULL
&&
1135 options
.permit_local_command
)
1136 ssh_local_cmd(options
.local_command
);
1139 * If requested and we are not interested in replies to remote
1140 * forwarding requests, then let ssh continue in the background.
1142 if (fork_after_authentication_flag
&&
1143 (!options
.exit_on_forward_failure
||
1144 options
.num_remote_forwards
== 0)) {
1145 fork_after_authentication_flag
= 0;
1146 if (daemon(1, 1) < 0)
1147 fatal("daemon() failed: %.200s", strerror(errno
));
1151 * If a command was specified on the command line, execute the
1152 * command now. Otherwise request the server to start a shell.
1154 if (buffer_len(&command
) > 0) {
1155 int len
= buffer_len(&command
);
1158 debug("Sending command: %.*s", len
,
1159 (u_char
*)buffer_ptr(&command
));
1160 packet_start(SSH_CMSG_EXEC_CMD
);
1161 packet_put_string(buffer_ptr(&command
), buffer_len(&command
));
1163 packet_write_wait();
1165 debug("Requesting shell.");
1166 packet_start(SSH_CMSG_EXEC_SHELL
);
1168 packet_write_wait();
1171 /* Enter the interactive session. */
1172 return client_loop(have_tty
, tty_flag
?
1173 options
.escape_char
: SSH_ESCAPECHAR_NONE
, 0);
1176 /* request pty/x11/agent/tcpfwd/shell for channel */
1178 ssh_session2_setup(int id
, void *arg
)
1180 extern char **environ
;
1181 const char *display
;
1182 int interactive
= tty_flag
;
1184 display
= getenv("DISPLAY");
1185 if (options
.forward_x11
&& display
!= NULL
) {
1187 /* Get reasonable local authentication information. */
1188 client_x11_get_proto(display
, options
.xauth_location
,
1189 options
.forward_x11_trusted
, &proto
, &data
);
1190 /* Request forwarding with authentication spoofing. */
1191 debug("Requesting X11 forwarding with authentication "
1193 x11_request_forwarding_with_spoofing(id
, display
, proto
, data
);
1195 /* XXX wait for reply */
1198 check_agent_present();
1199 if (options
.forward_agent
) {
1200 debug("Requesting authentication agent forwarding.");
1201 channel_request_start(id
, "auth-agent-req@openssh.com", 0);
1205 client_session2_setup(id
, tty_flag
, subsystem_flag
, getenv("TERM"),
1206 NULL
, fileno(stdin
), &command
, environ
);
1208 packet_set_interactive(interactive
);
1211 /* open new channel for a session */
1213 ssh_session2_open(void)
1216 int window
, packetmax
, in
, out
, err
;
1218 if (stdin_null_flag
) {
1219 in
= open(_PATH_DEVNULL
, O_RDONLY
);
1221 in
= dup(STDIN_FILENO
);
1223 out
= dup(STDOUT_FILENO
);
1224 err
= dup(STDERR_FILENO
);
1226 if (in
< 0 || out
< 0 || err
< 0)
1227 fatal("dup() in/out/err failed");
1229 /* enable nonblocking unless tty */
1237 window
= CHAN_SES_WINDOW_DEFAULT
;
1238 packetmax
= CHAN_SES_PACKET_DEFAULT
;
1244 "session", SSH_CHANNEL_OPENING
, in
, out
, err
,
1245 window
, packetmax
, CHAN_EXTENDED_WRITE
,
1246 "client-session", /*nonblock*/0);
1248 debug3("ssh_session2_open: channel_new: %d", c
->self
);
1250 channel_send_open(c
->self
);
1252 channel_register_open_confirm(c
->self
,
1253 ssh_session2_setup
, NULL
);
1263 /* XXX should be pre-session */
1264 ssh_init_forwarding();
1266 if (!no_shell_flag
|| (datafellows
& SSH_BUG_DUMMYCHAN
))
1267 id
= ssh_session2_open();
1269 /* If we don't expect to open a new session, then disallow it */
1270 if (options
.control_master
== SSHCTL_MASTER_NO
&&
1271 (datafellows
& SSH_NEW_OPENSSH
)) {
1272 debug("Requesting no-more-sessions@openssh.com");
1273 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
1274 packet_put_cstring("no-more-sessions@openssh.com");
1279 /* Execute a local command */
1280 if (options
.local_command
!= NULL
&&
1281 options
.permit_local_command
)
1282 ssh_local_cmd(options
.local_command
);
1284 /* Start listening for multiplex clients */
1287 /* If requested, let ssh continue in the background. */
1288 if (fork_after_authentication_flag
) {
1289 fork_after_authentication_flag
= 0;
1290 if (daemon(1, 1) < 0)
1291 fatal("daemon() failed: %.200s", strerror(errno
));
1294 if (options
.use_roaming
)
1297 return client_loop(tty_flag
, tty_flag
?
1298 options
.escape_char
: SSH_ESCAPECHAR_NONE
, id
);
1302 load_public_identity_files(void)
1304 char *filename
, *cp
, thishost
[NI_MAXHOST
];
1305 char *pwdir
= NULL
, *pwname
= NULL
;
1310 char *identity_files
[SSH_MAX_IDENTITY_FILES
];
1311 Key
*identity_keys
[SSH_MAX_IDENTITY_FILES
];
1312 #ifdef ENABLE_PKCS11
1318 bzero(identity_files
, sizeof(identity_files
));
1319 bzero(identity_keys
, sizeof(identity_keys
));
1321 #ifdef ENABLE_PKCS11
1322 if (options
.pkcs11_provider
!= NULL
&&
1323 options
.num_identity_files
< SSH_MAX_IDENTITY_FILES
&&
1324 (pkcs11_init(!options
.batch_mode
) == 0) &&
1325 (nkeys
= pkcs11_add_provider(options
.pkcs11_provider
, NULL
,
1327 for (i
= 0; i
< nkeys
; i
++) {
1328 if (n_ids
>= SSH_MAX_IDENTITY_FILES
) {
1332 identity_keys
[n_ids
] = keys
[i
];
1333 identity_files
[n_ids
] =
1334 xstrdup(options
.pkcs11_provider
); /* XXX */
1339 #endif /* ENABLE_PKCS11 */
1340 if ((pw
= getpwuid(original_real_uid
)) == NULL
)
1341 fatal("load_public_identity_files: getpwuid failed");
1342 pwname
= xstrdup(pw
->pw_name
);
1343 pwdir
= xstrdup(pw
->pw_dir
);
1344 if (gethostname(thishost
, sizeof(thishost
)) == -1)
1345 fatal("load_public_identity_files: gethostname: %s",
1347 for (i
= 0; i
< options
.num_identity_files
; i
++) {
1348 if (n_ids
>= SSH_MAX_IDENTITY_FILES
) {
1349 xfree(options
.identity_files
[i
]);
1352 cp
= tilde_expand_filename(options
.identity_files
[i
],
1354 filename
= percent_expand(cp
, "d", pwdir
,
1355 "u", pwname
, "l", thishost
, "h", host
,
1356 "r", options
.user
, (char *)NULL
);
1358 public = key_load_public(filename
, NULL
);
1359 debug("identity file %s type %d", filename
,
1360 public ? public->type
: -1);
1361 xfree(options
.identity_files
[i
]);
1362 identity_files
[n_ids
] = filename
;
1363 identity_keys
[n_ids
] = public;
1365 if (++n_ids
>= SSH_MAX_IDENTITY_FILES
)
1368 /* Try to add the certificate variant too */
1369 xasprintf(&cp
, "%s-cert", filename
);
1370 public = key_load_public(cp
, NULL
);
1371 debug("identity file %s type %d", cp
,
1372 public ? public->type
: -1);
1373 if (public == NULL
) {
1377 if (!key_is_cert(public)) {
1378 debug("%s: key %s type %s is not a certificate",
1379 __func__
, cp
, key_type(public));
1384 identity_keys
[n_ids
] = public;
1385 /* point to the original path, most likely the private key */
1386 identity_files
[n_ids
] = xstrdup(filename
);
1389 options
.num_identity_files
= n_ids
;
1390 memcpy(options
.identity_files
, identity_files
, sizeof(identity_files
));
1391 memcpy(options
.identity_keys
, identity_keys
, sizeof(identity_keys
));
1393 bzero(pwname
, strlen(pwname
));
1395 bzero(pwdir
, strlen(pwdir
));