1 /* $NetBSD: ssh.c,v 1.1.1.2 2009/12/27 01:07:12 christos Exp $ */
2 /* $OpenBSD: ssh.c,v 1.326 2009/07/02 02:11:47 dtucker Exp $ */
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * Ssh client program. This program can be used to log into a remote machine.
8 * The software supports strong authentication, encryption, and forwarding
9 * of X11, TCP/IP, and authentication connections.
11 * As far as I am concerned, the code I have written for this software
12 * can be used freely for any purpose. Any derived versions of this
13 * software must be clearly marked as such, and if the derived work is
14 * incompatible with the protocol description in the RFC file, it must be
15 * called by a name other than "ssh" or "Secure Shell".
17 * Copyright (c) 1999 Niels Provos. All rights reserved.
18 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
20 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
21 * in Canada (German citizen).
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
32 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
33 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
35 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
36 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
41 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45 __RCSID("$NetBSD: ssh.c,v 1.2 2009/06/07 22:38:47 christos Exp $");
46 #include <sys/types.h>
47 #include <sys/param.h>
48 #include <sys/ioctl.h>
49 #include <sys/param.h>
50 #include <sys/queue.h>
51 #include <sys/resource.h>
52 #include <sys/socket.h>
69 #include <openssl/evp.h>
70 #include <openssl/err.h>
84 #include "pathnames.h"
86 #include "clientloop.h"
89 #include "sshconnect.h"
103 extern char *__progname
;
105 /* Flag indicating whether debug mode is on. May be set on the command line. */
108 /* Flag indicating whether a tty should be allocated */
111 int force_tty_flag
= 0;
113 /* don't exec a shell */
114 int no_shell_flag
= 0;
117 * Flag indicating that nothing should be read from stdin. This can be set
118 * on the command line.
120 int stdin_null_flag
= 0;
123 * Flag indicating that ssh should fork after authentication. This is useful
124 * so that the passphrase can be entered manually, and then ssh goes to the
127 int fork_after_authentication_flag
= 0;
130 * General data structure for command line options and options configurable
131 * in configuration files. See readconf.h.
135 /* optional user configfile */
139 * Name of the host we are connecting to. This is the name given on the
140 * command line, or the HostName specified for the user-supplied name in a
141 * configuration file.
145 /* socket address the host resolves to */
146 struct sockaddr_storage hostaddr
;
148 /* Private host keys. */
149 Sensitive sensitive_data
;
151 /* Original real UID. */
152 uid_t original_real_uid
;
153 uid_t original_effective_uid
;
155 /* command to be executed */
158 /* Should we execute a command or invoke a subsystem? */
159 int subsystem_flag
= 0;
161 /* # of replies received for global requests */
162 static int remote_forward_confirms_received
= 0;
164 /* pid of proxycommand child process */
165 pid_t proxy_command_pid
= 0;
168 extern int muxserver_sock
;
169 extern u_int muxclient_command
;
172 /* Prints a help message to the user. This function never returns. */
178 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
179 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
180 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
181 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
182 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
183 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
188 static int ssh_session(void);
189 static int ssh_session2(void);
190 static void load_public_identity_files(void);
192 /* from muxclient.c */
193 void muxclient(const char *);
194 void muxserver_listen(void);
197 * Main program for the ssh client.
200 main(int ac
, char **av
)
202 int i
, r
, opt
, exit_status
, use_syslog
;
203 char *p
, *cp
, *line
, *argv0
, buf
[MAXPATHLEN
];
206 int dummy
, timeout_ms
;
207 extern int optind
, optreset
;
212 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
216 * Save the original real uid. It will be needed later (uid-swapping
217 * may clobber the real uid).
219 original_real_uid
= getuid();
220 original_effective_uid
= geteuid();
223 * Use uid-swapping to give up root privileges for the duration of
224 * option processing. We will re-instantiate the rights when we are
225 * ready to create the privileged port, and will permanently drop
226 * them when the port has been created (actually, when the connection
227 * has been made, as we may need to create the port several times).
231 /* If we are installed setuid root be careful to not drop core. */
232 if (original_real_uid
!= original_effective_uid
) {
234 rlim
.rlim_cur
= rlim
.rlim_max
= 0;
235 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
236 fatal("setrlimit failed: %.100s", strerror(errno
));
239 pw
= getpwuid(original_real_uid
);
241 logit("You don't exist, go away!");
244 /* Take a copy of the returned structure. */
248 * Set our umask to something reasonable, as some files are created
249 * with the default umask. This will make them world-readable but
250 * writable only by the owner, which is ok for all files for which we
251 * don't set the modes explicitly.
256 * Initialize option structure to indicate that no values have been
259 initialize_options(&options
);
261 /* Parse command-line arguments. */
267 while ((opt
= getopt(ac
, av
, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
268 "ACD:F:I:KL:MNO:PR:S:TVw:XYy")) != -1) {
271 options
.protocol
= SSH_PROTO_1
;
274 options
.protocol
= SSH_PROTO_2
;
277 options
.address_family
= AF_INET
;
280 options
.address_family
= AF_INET6
;
286 fork_after_authentication_flag
= 1;
290 options
.forward_x11
= 0;
293 options
.forward_x11
= 1;
299 options
.forward_x11
= 1;
300 options
.forward_x11_trusted
= 1;
303 options
.gateway_ports
= 1;
306 if (strcmp(optarg
, "check") == 0)
307 muxclient_command
= SSHMUX_COMMAND_ALIVE_CHECK
;
308 else if (strcmp(optarg
, "exit") == 0)
309 muxclient_command
= SSHMUX_COMMAND_TERMINATE
;
311 fatal("Invalid multiplex command.");
313 case 'P': /* deprecated */
314 options
.use_privileged_port
= 0;
317 options
.forward_agent
= 0;
320 options
.forward_agent
= 1;
323 options
.gss_deleg_creds
= 0;
326 options
.gss_authentication
= 1;
327 options
.gss_deleg_creds
= 1;
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_VERSION
, 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
) {
377 "Bad tun device '%s'\n", optarg
);
382 options
.log_level
= SYSLOG_LEVEL_QUIET
;
385 if (optarg
[0] == '^' && optarg
[2] == 0 &&
386 (u_char
) optarg
[1] >= 64 &&
387 (u_char
) optarg
[1] < 128)
388 options
.escape_char
= (u_char
) optarg
[1] & 31;
389 else if (strlen(optarg
) == 1)
390 options
.escape_char
= (u_char
) optarg
[0];
391 else if (strcmp(optarg
, "none") == 0)
392 options
.escape_char
= SSH_ESCAPECHAR_NONE
;
394 fprintf(stderr
, "Bad escape character '%s'.\n",
400 if (ciphers_valid(optarg
)) {
402 options
.ciphers
= xstrdup(optarg
);
403 options
.cipher
= SSH_CIPHER_INVALID
;
406 options
.cipher
= cipher_number(optarg
);
407 if (options
.cipher
== -1) {
409 "Unknown cipher type '%s'\n",
413 if (options
.cipher
== SSH_CIPHER_3DES
)
414 options
.ciphers
= "3des-cbc";
415 else if (options
.cipher
== SSH_CIPHER_BLOWFISH
)
416 options
.ciphers
= "blowfish-cbc";
418 options
.ciphers
= (char *)-1;
422 if (mac_valid(optarg
))
423 options
.macs
= xstrdup(optarg
);
425 fprintf(stderr
, "Unknown mac type '%s'\n",
431 if (options
.control_master
== SSHCTL_MASTER_YES
)
432 options
.control_master
= SSHCTL_MASTER_ASK
;
434 options
.control_master
= SSHCTL_MASTER_YES
;
437 options
.port
= a2port(optarg
);
438 if (options
.port
<= 0) {
439 fprintf(stderr
, "Bad port '%s'\n", optarg
);
444 options
.user
= optarg
;
448 if (parse_forward(&fwd
, optarg
, 0, 0))
449 add_local_forward(&options
, &fwd
);
452 "Bad local forwarding specification '%s'\n",
459 if (parse_forward(&fwd
, optarg
, 0, 1)) {
460 add_remote_forward(&options
, &fwd
);
463 "Bad remote forwarding specification "
470 if (parse_forward(&fwd
, optarg
, 1, 0)) {
471 add_local_forward(&options
, &fwd
);
474 "Bad dynamic forwarding specification "
481 options
.compression
= 1;
489 /* ensure that the user doesn't try to backdoor a */
490 /* null cipher switch on an interactive session */
491 /* so explicitly disable it no matter what */
492 options
.none_switch
=0;
496 line
= xstrdup(optarg
);
497 if (process_config_line(&options
, host
? host
: "",
498 line
, "command-line", 0, &dummy
) != 0)
506 if (options
.control_path
!= NULL
)
507 free(options
.control_path
);
508 options
.control_path
= xstrdup(optarg
);
511 options
.bind_address
= optarg
;
524 if (ac
> 0 && !host
&& **av
!= '-') {
525 if (strrchr(*av
, '@')) {
527 cp
= strrchr(p
, '@');
528 if (cp
== NULL
|| cp
== p
)
536 optind
= optreset
= 1;
542 /* Check that we got a host name. */
546 SSLeay_add_all_algorithms();
547 ERR_load_crypto_strings();
549 /* Initialize the command to execute on remote host. */
550 buffer_init(&command
);
553 * Save the command to execute on the remote host in a buffer. There
554 * is no limit on the length of the command, except by the maximum
555 * packet size. Also sets the tty flag if there is no command.
558 /* No command specified - execute shell on a tty. */
560 if (subsystem_flag
) {
562 "You must specify a subsystem to invoke.\n");
566 /* A command has been specified. Store it into the buffer. */
567 for (i
= 0; i
< ac
; i
++) {
569 buffer_append(&command
, " ", 1);
570 buffer_append(&command
, av
[i
], strlen(av
[i
]));
574 /* Cannot fork to background if no command. */
575 if (fork_after_authentication_flag
&& buffer_len(&command
) == 0 &&
577 fatal("Cannot fork into background without a command "
580 /* Allocate a tty by default if no command specified. */
581 if (buffer_len(&command
) == 0)
587 /* Do not allocate a tty if stdin is not a tty. */
588 if ((!isatty(fileno(stdin
)) || stdin_null_flag
) && !force_tty_flag
) {
590 logit("Pseudo-terminal will not be allocated because "
591 "stdin is not a terminal.");
596 * Initialize "log" output. Since we are the client all output
597 * actually goes to stderr.
600 options
.log_level
== -1 ? SYSLOG_LEVEL_INFO
: options
.log_level
,
601 SYSLOG_FACILITY_USER
, !use_syslog
);
604 * Read per-user configuration file. Ignore the system wide config
605 * file if the user specifies a config file on the command line.
607 if (config
!= NULL
) {
608 if (!read_config_file(config
, host
, &options
, 0))
609 fatal("Can't open user config file %.100s: "
610 "%.100s", config
, strerror(errno
));
612 r
= snprintf(buf
, sizeof buf
, "%s/%s", pw
->pw_dir
,
613 _PATH_SSH_USER_CONFFILE
);
614 if (r
> 0 && (size_t)r
< sizeof(buf
))
615 (void)read_config_file(buf
, host
, &options
, 1);
617 /* Read systemwide configuration file after use config. */
618 (void)read_config_file(_PATH_HOST_CONFIG_FILE
, host
,
622 /* Fill configuration defaults. */
623 fill_default_options(&options
);
625 channel_set_af(options
.address_family
);
628 log_init(argv0
, options
.log_level
, SYSLOG_FACILITY_USER
, !use_syslog
);
630 if (options
.user
== NULL
)
631 options
.user
= xstrdup(pw
->pw_name
);
633 /* Get default port if port has not been set. */
634 if (options
.port
== 0) {
635 sp
= getservbyname(SSH_SERVICE_NAME
, "tcp");
636 options
.port
= sp
? ntohs(sp
->s_port
) : SSH_DEFAULT_PORT
;
639 if (options
.local_command
!= NULL
) {
640 char thishost
[NI_MAXHOST
];
642 if (gethostname(thishost
, sizeof(thishost
)) == -1)
643 fatal("gethostname: %s", strerror(errno
));
644 snprintf(buf
, sizeof(buf
), "%d", options
.port
);
645 debug3("expanding LocalCommand: %s", options
.local_command
);
646 cp
= options
.local_command
;
647 options
.local_command
= percent_expand(cp
, "d", pw
->pw_dir
,
648 "h", options
.hostname
? options
.hostname
: host
,
649 "l", thishost
, "n", host
, "r", options
.user
, "p", buf
,
650 "u", pw
->pw_name
, (char *)NULL
);
651 debug3("expanded LocalCommand: %s", options
.local_command
);
655 if (options
.hostname
!= NULL
)
656 host
= options
.hostname
;
658 /* force lowercase for hostkey matching */
659 if (options
.host_key_alias
!= NULL
) {
660 for (p
= options
.host_key_alias
; *p
; p
++)
661 if (isupper((unsigned char)*p
))
662 *p
= (char)tolower((unsigned char)*p
);
665 if (options
.proxy_command
!= NULL
&&
666 strcmp(options
.proxy_command
, "none") == 0) {
667 xfree(options
.proxy_command
);
668 options
.proxy_command
= NULL
;
670 if (options
.control_path
!= NULL
&&
671 strcmp(options
.control_path
, "none") == 0) {
672 xfree(options
.control_path
);
673 options
.control_path
= NULL
;
676 if (options
.control_path
!= NULL
) {
677 char thishost
[NI_MAXHOST
];
679 if (gethostname(thishost
, sizeof(thishost
)) == -1)
680 fatal("gethostname: %s", strerror(errno
));
681 snprintf(buf
, sizeof(buf
), "%d", options
.port
);
682 cp
= tilde_expand_filename(options
.control_path
,
684 xfree(options
.control_path
);
685 options
.control_path
= percent_expand(cp
, "p", buf
, "h", host
,
686 "r", options
.user
, "l", thishost
, (char *)NULL
);
689 if (muxclient_command
!= 0 && options
.control_path
== NULL
)
690 fatal("No ControlPath specified for \"-O\" command");
691 if (options
.control_path
!= NULL
)
692 muxclient(options
.control_path
);
694 timeout_ms
= options
.connection_timeout
* 1000;
696 /* Open a connection to the remote host. */
697 if (ssh_connect(host
, &hostaddr
, options
.port
,
698 options
.address_family
, options
.connection_attempts
, &timeout_ms
,
699 options
.tcp_keep_alive
,
700 original_effective_uid
== 0 && options
.use_privileged_port
,
701 options
.proxy_command
) != 0)
705 debug3("timeout: %d ms remain after connect", timeout_ms
);
708 * If we successfully made the connection, load the host private key
709 * in case we will need it later for combined rsa-rhosts
710 * authentication. This must be done before releasing extra
711 * privileges, because the file is only readable by root.
712 * If we cannot access the private keys, load the public keys
713 * instead and try to execute the ssh-keysign helper instead.
715 sensitive_data
.nkeys
= 0;
716 sensitive_data
.keys
= NULL
;
717 sensitive_data
.external_keysign
= 0;
718 if (options
.rhosts_rsa_authentication
||
719 options
.hostbased_authentication
) {
720 sensitive_data
.nkeys
= 3;
721 sensitive_data
.keys
= xcalloc(sensitive_data
.nkeys
,
725 sensitive_data
.keys
[0] = key_load_private_type(KEY_RSA1
,
726 _PATH_HOST_KEY_FILE
, "", NULL
, NULL
);
727 sensitive_data
.keys
[1] = key_load_private_type(KEY_DSA
,
728 _PATH_HOST_DSA_KEY_FILE
, "", NULL
, NULL
);
729 sensitive_data
.keys
[2] = key_load_private_type(KEY_RSA
,
730 _PATH_HOST_RSA_KEY_FILE
, "", NULL
, NULL
);
733 if (options
.hostbased_authentication
== 1 &&
734 sensitive_data
.keys
[0] == NULL
&&
735 sensitive_data
.keys
[1] == NULL
&&
736 sensitive_data
.keys
[2] == NULL
) {
737 sensitive_data
.keys
[1] = key_load_public(
738 _PATH_HOST_DSA_KEY_FILE
, NULL
);
739 sensitive_data
.keys
[2] = key_load_public(
740 _PATH_HOST_RSA_KEY_FILE
, NULL
);
741 sensitive_data
.external_keysign
= 1;
745 * Get rid of any extra privileges that we may have. We will no
746 * longer need them. Also, extra privileges could make it very hard
747 * to read identity files and other non-world-readable files from the
748 * user's home directory if it happens to be on a NFS volume where
749 * root is mapped to nobody.
751 if (original_effective_uid
== 0) {
753 permanently_set_uid(pw
);
757 * Now that we are back to our own permissions, create ~/.ssh
758 * directory if it doesn't already exist.
760 r
= snprintf(buf
, sizeof buf
, "%s%s%s", pw
->pw_dir
,
761 strcmp(pw
->pw_dir
, "/") ? "/" : "", _PATH_SSH_USER_DIR
);
762 if (r
> 0 && (size_t)r
< sizeof(buf
) && stat(buf
, &st
) < 0)
763 if (mkdir(buf
, 0700) < 0)
764 error("Could not create directory '%.200s'.", buf
);
766 /* load options.identity_files */
767 load_public_identity_files();
769 /* Expand ~ in known host file names. */
771 options
.system_hostfile
=
772 tilde_expand_filename(options
.system_hostfile
, original_real_uid
);
773 options
.user_hostfile
=
774 tilde_expand_filename(options
.user_hostfile
, original_real_uid
);
775 options
.system_hostfile2
=
776 tilde_expand_filename(options
.system_hostfile2
, original_real_uid
);
777 options
.user_hostfile2
=
778 tilde_expand_filename(options
.user_hostfile2
, original_real_uid
);
780 signal(SIGPIPE
, SIG_IGN
); /* ignore SIGPIPE early */
782 /* Log into the remote system. Never returns if the login fails. */
783 ssh_login(&sensitive_data
, host
, (struct sockaddr
*)&hostaddr
,
786 /* We no longer need the private host keys. Clear them now. */
787 if (sensitive_data
.nkeys
!= 0) {
788 for (i
= 0; i
< sensitive_data
.nkeys
; i
++) {
789 if (sensitive_data
.keys
[i
] != NULL
) {
790 /* Destroys contents safely */
791 debug3("clear hostkey %d", i
);
792 key_free(sensitive_data
.keys
[i
]);
793 sensitive_data
.keys
[i
] = NULL
;
796 xfree(sensitive_data
.keys
);
798 for (i
= 0; i
< options
.num_identity_files
; i
++) {
799 if (options
.identity_files
[i
]) {
800 xfree(options
.identity_files
[i
]);
801 options
.identity_files
[i
] = NULL
;
803 if (options
.identity_keys
[i
]) {
804 key_free(options
.identity_keys
[i
]);
805 options
.identity_keys
[i
] = NULL
;
809 exit_status
= compat20
? ssh_session2() : ssh_session();
812 if (options
.control_path
!= NULL
&& muxserver_sock
!= -1)
813 unlink(options
.control_path
);
816 * Send SIGHUP to proxy command if used. We don't wait() in
817 * case it hangs and instead rely on init to reap the child
819 if (proxy_command_pid
> 1)
820 kill(proxy_command_pid
, SIGHUP
);
825 /* Callback for remote forward global requests */
827 ssh_confirm_remote_forward(int type
, u_int32_t seq
, void *ctxt
)
829 Forward
*rfwd
= (Forward
*)ctxt
;
831 /* XXX verbose() on failure? */
832 debug("remote forward %s for: listen %d, connect %s:%d",
833 type
== SSH2_MSG_REQUEST_SUCCESS
? "success" : "failure",
834 rfwd
->listen_port
, rfwd
->connect_host
, rfwd
->connect_port
);
835 if (type
== SSH2_MSG_REQUEST_SUCCESS
&& rfwd
->listen_port
== 0) {
836 logit("Allocated port %u for remote forward to %s:%d",
838 rfwd
->connect_host
, rfwd
->connect_port
);
841 if (type
== SSH2_MSG_REQUEST_FAILURE
) {
842 if (options
.exit_on_forward_failure
)
843 fatal("Error: remote port forwarding failed for "
844 "listen port %d", rfwd
->listen_port
);
846 logit("Warning: remote port forwarding failed for "
847 "listen port %d", rfwd
->listen_port
);
849 if (++remote_forward_confirms_received
== options
.num_remote_forwards
) {
850 debug("All remote forwarding requests processed");
851 if (fork_after_authentication_flag
) {
852 fork_after_authentication_flag
= 0;
853 if (daemon(1, 1) < 0)
854 fatal("daemon() failed: %.200s",
861 ssh_init_forwarding(void)
866 /* Initiate local TCP/IP port forwardings. */
867 for (i
= 0; i
< options
.num_local_forwards
; i
++) {
868 debug("Local connections to %.200s:%d forwarded to remote "
870 (options
.local_forwards
[i
].listen_host
== NULL
) ?
871 (options
.gateway_ports
? "*" : "LOCALHOST") :
872 options
.local_forwards
[i
].listen_host
,
873 options
.local_forwards
[i
].listen_port
,
874 options
.local_forwards
[i
].connect_host
,
875 options
.local_forwards
[i
].connect_port
);
876 success
+= channel_setup_local_fwd_listener(
877 options
.local_forwards
[i
].listen_host
,
878 options
.local_forwards
[i
].listen_port
,
879 options
.local_forwards
[i
].connect_host
,
880 options
.local_forwards
[i
].connect_port
,
881 options
.gateway_ports
);
883 if (i
> 0 && success
!= i
&& options
.exit_on_forward_failure
)
884 fatal("Could not request local forwarding.");
885 if (i
> 0 && success
== 0)
886 error("Could not request local forwarding.");
888 /* Initiate remote TCP/IP port forwardings. */
889 for (i
= 0; i
< options
.num_remote_forwards
; i
++) {
890 debug("Remote connections from %.200s:%d forwarded to "
891 "local address %.200s:%d",
892 (options
.remote_forwards
[i
].listen_host
== NULL
) ?
893 "LOCALHOST" : options
.remote_forwards
[i
].listen_host
,
894 options
.remote_forwards
[i
].listen_port
,
895 options
.remote_forwards
[i
].connect_host
,
896 options
.remote_forwards
[i
].connect_port
);
897 if (channel_request_remote_forwarding(
898 options
.remote_forwards
[i
].listen_host
,
899 options
.remote_forwards
[i
].listen_port
,
900 options
.remote_forwards
[i
].connect_host
,
901 options
.remote_forwards
[i
].connect_port
) < 0) {
902 if (options
.exit_on_forward_failure
)
903 fatal("Could not request remote forwarding.");
905 logit("Warning: Could not request remote "
908 client_register_global_confirm(ssh_confirm_remote_forward
,
909 &options
.remote_forwards
[i
]);
912 /* Initiate tunnel forwarding. */
913 if (options
.tun_open
!= SSH_TUNMODE_NO
) {
914 if (client_request_tun_fwd(options
.tun_open
,
915 options
.tun_local
, options
.tun_remote
) == -1) {
916 if (options
.exit_on_forward_failure
)
917 fatal("Could not request tunnel forwarding.");
919 error("Could not request tunnel forwarding.");
925 check_agent_present(void)
927 if (options
.forward_agent
) {
928 /* Clear agent forwarding if we don't have an agent. */
929 if (!ssh_agent_present())
930 options
.forward_agent
= 0;
944 /* Enable compression if requested. */
945 if (options
.compression
) {
946 debug("Requesting compression at level %d.",
947 options
.compression_level
);
949 if (options
.compression_level
< 1 ||
950 options
.compression_level
> 9)
951 fatal("Compression level must be from 1 (fast) to "
954 /* Send the request. */
955 packet_start(SSH_CMSG_REQUEST_COMPRESSION
);
956 packet_put_int(options
.compression_level
);
959 type
= packet_read();
960 if (type
== SSH_SMSG_SUCCESS
)
961 packet_start_compression(options
.compression_level
);
962 else if (type
== SSH_SMSG_FAILURE
)
963 logit("Warning: Remote host refused compression.");
965 packet_disconnect("Protocol error waiting for "
966 "compression response.");
968 /* Allocate a pseudo tty if appropriate. */
970 debug("Requesting pty.");
972 /* Start the packet. */
973 packet_start(SSH_CMSG_REQUEST_PTY
);
975 /* Store TERM in the packet. There is no limit on the
976 length of the string. */
980 packet_put_cstring(cp
);
982 /* Store window size in the packet. */
983 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) < 0)
984 memset(&ws
, 0, sizeof(ws
));
985 packet_put_int((u_int
)ws
.ws_row
);
986 packet_put_int((u_int
)ws
.ws_col
);
987 packet_put_int((u_int
)ws
.ws_xpixel
);
988 packet_put_int((u_int
)ws
.ws_ypixel
);
990 /* Store tty modes in the packet. */
991 tty_make_modes(fileno(stdin
), NULL
);
993 /* Send the packet, and wait for it to leave. */
997 /* Read response from the server. */
998 type
= packet_read();
999 if (type
== SSH_SMSG_SUCCESS
) {
1002 } else if (type
== SSH_SMSG_FAILURE
)
1003 logit("Warning: Remote host failed or refused to "
1004 "allocate a pseudo tty.");
1006 packet_disconnect("Protocol error waiting for pty "
1007 "request response.");
1009 /* Request X11 forwarding if enabled and DISPLAY is set. */
1010 display
= getenv("DISPLAY");
1011 if (options
.forward_x11
&& display
!= NULL
) {
1013 /* Get reasonable local authentication information. */
1014 client_x11_get_proto(display
, options
.xauth_location
,
1015 options
.forward_x11_trusted
, &proto
, &data
);
1016 /* Request forwarding with authentication spoofing. */
1017 debug("Requesting X11 forwarding with authentication "
1019 x11_request_forwarding_with_spoofing(0, display
, proto
, data
);
1021 /* Read response from the server. */
1022 type
= packet_read();
1023 if (type
== SSH_SMSG_SUCCESS
) {
1025 } else if (type
== SSH_SMSG_FAILURE
) {
1026 logit("Warning: Remote host denied X11 forwarding.");
1028 packet_disconnect("Protocol error waiting for X11 "
1032 /* Tell the packet module whether this is an interactive session. */
1033 packet_set_interactive(interactive
);
1035 /* Request authentication agent forwarding if appropriate. */
1036 check_agent_present();
1038 if (options
.forward_agent
) {
1039 debug("Requesting authentication agent forwarding.");
1040 auth_request_forwarding();
1042 /* Read response from the server. */
1043 type
= packet_read();
1045 if (type
!= SSH_SMSG_SUCCESS
)
1046 logit("Warning: Remote host denied authentication agent forwarding.");
1049 /* Initiate port forwardings. */
1050 ssh_init_forwarding();
1052 /* Execute a local command */
1053 if (options
.local_command
!= NULL
&&
1054 options
.permit_local_command
)
1055 ssh_local_cmd(options
.local_command
);
1058 * If requested and we are not interested in replies to remote
1059 * forwarding requests, then let ssh continue in the background.
1061 if (fork_after_authentication_flag
&&
1062 (!options
.exit_on_forward_failure
||
1063 options
.num_remote_forwards
== 0)) {
1064 fork_after_authentication_flag
= 0;
1065 if (daemon(1, 1) < 0)
1066 fatal("daemon() failed: %.200s", strerror(errno
));
1070 * If a command was specified on the command line, execute the
1071 * command now. Otherwise request the server to start a shell.
1073 if (buffer_len(&command
) > 0) {
1074 int len
= buffer_len(&command
);
1077 debug("Sending command: %.*s", len
,
1078 (u_char
*)buffer_ptr(&command
));
1079 packet_start(SSH_CMSG_EXEC_CMD
);
1080 packet_put_string(buffer_ptr(&command
), buffer_len(&command
));
1082 packet_write_wait();
1084 debug("Requesting shell.");
1085 packet_start(SSH_CMSG_EXEC_SHELL
);
1087 packet_write_wait();
1090 /* Enter the interactive session. */
1091 return client_loop(have_tty
, tty_flag
?
1092 options
.escape_char
: SSH_ESCAPECHAR_NONE
, 0);
1095 /* request pty/x11/agent/tcpfwd/shell for channel */
1097 ssh_session2_setup(int id
, void *arg
)
1099 extern char **environ
;
1100 const char *display
;
1101 int interactive
= tty_flag
;
1103 display
= getenv("DISPLAY");
1104 if (options
.forward_x11
&& display
!= NULL
) {
1106 /* Get reasonable local authentication information. */
1107 client_x11_get_proto(display
, options
.xauth_location
,
1108 options
.forward_x11_trusted
, &proto
, &data
);
1109 /* Request forwarding with authentication spoofing. */
1110 debug("Requesting X11 forwarding with authentication "
1112 x11_request_forwarding_with_spoofing(id
, display
, proto
, data
);
1114 /* XXX wait for reply */
1117 check_agent_present();
1118 if (options
.forward_agent
) {
1119 debug("Requesting authentication agent forwarding.");
1120 channel_request_start(id
, "auth-agent-req@openssh.com", 0);
1124 client_session2_setup(id
, tty_flag
, subsystem_flag
, getenv("TERM"),
1125 NULL
, fileno(stdin
), &command
, environ
);
1127 packet_set_interactive(interactive
);
1130 /* open new channel for a session */
1132 ssh_session2_open(void)
1135 int window
, packetmax
, in
, out
, err
;
1138 socklen_t socksizelen
= sizeof(int);
1140 if (stdin_null_flag
) {
1141 in
= open(_PATH_DEVNULL
, O_RDONLY
);
1143 in
= dup(STDIN_FILENO
);
1145 out
= dup(STDOUT_FILENO
);
1146 err
= dup(STDERR_FILENO
);
1148 if (in
< 0 || out
< 0 || err
< 0)
1149 fatal("dup() in/out/err failed");
1151 /* enable nonblocking unless tty */
1159 /* we need to check to see if what they want to do about buffer */
1160 /* sizes here. In a hpn to nonhpn connection we want to limit */
1161 /* the window size to something reasonable in case the far side */
1162 /* has the large window bug. In hpn to hpn connection we want to */
1163 /* use the max window size but allow the user to override it */
1164 /* lastly if they disabled hpn then use the ssh std window size */
1166 /* so why don't we just do a getsockopt() here and set the */
1167 /* ssh window to that? In the case of a autotuning receive */
1168 /* window the window would get stuck at the initial buffer */
1169 /* size generally less than 96k. Therefore we need to set the */
1170 /* maximum ssh window size to the maximum hpn buffer size */
1171 /* unless the user has specifically set the tcprcvbufpoll */
1172 /* to no. In which case we *can* just set the window to the */
1173 /* minimum of the hpn buffer size and tcp receive buffer size */
1176 options
.hpn_buffer_size
= CHAN_SES_WINDOW_DEFAULT
;
1178 options
.hpn_buffer_size
= 2*1024*1024;
1180 if (datafellows
& SSH_BUG_LARGEWINDOW
)
1182 debug("HPN to Non-HPN Connection");
1186 if (options
.tcp_rcv_buf_poll
<= 0)
1188 sock
= socket(AF_INET
, SOCK_STREAM
, 0);
1189 getsockopt(sock
, SOL_SOCKET
, SO_RCVBUF
,
1190 &socksize
, &socksizelen
);
1192 debug("socksize %d", socksize
);
1193 options
.hpn_buffer_size
= socksize
;
1194 debug ("HPNBufferSize set to TCP RWIN: %d", options
.hpn_buffer_size
);
1198 if (options
.tcp_rcv_buf
> 0)
1200 /*create a socket but don't connect it */
1201 /* we use that the get the rcv socket size */
1202 sock
= socket(AF_INET
, SOCK_STREAM
, 0);
1203 /* if they are using the tcp_rcv_buf option */
1204 /* attempt to set the buffer size to that */
1205 if (options
.tcp_rcv_buf
)
1206 setsockopt(sock
, SOL_SOCKET
, SO_RCVBUF
, (void *)&options
.tcp_rcv_buf
,
1207 sizeof(options
.tcp_rcv_buf
));
1208 getsockopt(sock
, SOL_SOCKET
, SO_RCVBUF
,
1209 &socksize
, &socksizelen
);
1211 debug("socksize %d", socksize
);
1212 options
.hpn_buffer_size
= socksize
;
1213 debug ("HPNBufferSize set to user TCPRcvBuf: %d", options
.hpn_buffer_size
);
1219 debug("Final hpn_buffer_size = %d", options
.hpn_buffer_size
);
1221 window
= options
.hpn_buffer_size
;
1223 channel_set_hpn(options
.hpn_disabled
, options
.hpn_buffer_size
);
1225 packetmax
= CHAN_SES_PACKET_DEFAULT
;
1231 "session", SSH_CHANNEL_OPENING
, in
, out
, err
,
1232 window
, packetmax
, CHAN_EXTENDED_WRITE
,
1233 "client-session", /*nonblock*/0);
1235 if ((options
.tcp_rcv_buf_poll
> 0) && (!options
.hpn_disabled
)) {
1236 c
->dynamic_window
= 1;
1237 debug ("Enabled Dynamic Window Scaling\n");
1239 debug3("ssh_session2_open: channel_new: %d", c
->self
);
1241 channel_send_open(c
->self
);
1243 channel_register_open_confirm(c
->self
,
1244 ssh_session2_setup
, NULL
);
1254 /* XXX should be pre-session */
1255 ssh_init_forwarding();
1257 if (!no_shell_flag
|| (datafellows
& SSH_BUG_DUMMYCHAN
))
1258 id
= ssh_session2_open();
1260 /* If we don't expect to open a new session, then disallow it */
1261 if (options
.control_master
== SSHCTL_MASTER_NO
&&
1262 (datafellows
& SSH_NEW_OPENSSH
)) {
1263 debug("Requesting no-more-sessions@openssh.com");
1264 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
1265 packet_put_cstring("no-more-sessions@openssh.com");
1270 /* Execute a local command */
1271 if (options
.local_command
!= NULL
&&
1272 options
.permit_local_command
)
1273 ssh_local_cmd(options
.local_command
);
1275 /* Start listening for multiplex clients */
1278 /* If requested, let ssh continue in the background. */
1279 if (fork_after_authentication_flag
) {
1280 fork_after_authentication_flag
= 0;
1281 if (daemon(1, 1) < 0)
1282 fatal("daemon() failed: %.200s", strerror(errno
));
1285 return client_loop(tty_flag
, tty_flag
?
1286 options
.escape_char
: SSH_ESCAPECHAR_NONE
, id
);
1290 load_public_identity_files(void)
1292 char *filename
, *cp
, thishost
[NI_MAXHOST
];
1293 char *pwdir
= NULL
, *pwname
= NULL
;
1300 if (options
.smartcard_device
!= NULL
&&
1301 options
.num_identity_files
< SSH_MAX_IDENTITY_FILES
&&
1302 (keys
= sc_get_keys(options
.smartcard_device
, NULL
)) != NULL
) {
1304 for (i
= 0; keys
[i
] != NULL
; i
++) {
1306 memmove(&options
.identity_files
[1],
1307 &options
.identity_files
[0],
1308 sizeof(char *) * (SSH_MAX_IDENTITY_FILES
- 1));
1309 memmove(&options
.identity_keys
[1],
1310 &options
.identity_keys
[0],
1311 sizeof(Key
*) * (SSH_MAX_IDENTITY_FILES
- 1));
1312 options
.num_identity_files
++;
1313 options
.identity_keys
[0] = keys
[i
];
1314 options
.identity_files
[0] = sc_get_key_label(keys
[i
]);
1316 if (options
.num_identity_files
> SSH_MAX_IDENTITY_FILES
)
1317 options
.num_identity_files
= SSH_MAX_IDENTITY_FILES
;
1321 #endif /* SMARTCARD */
1322 if ((pw
= getpwuid(original_real_uid
)) == NULL
)
1323 fatal("load_public_identity_files: getpwuid failed");
1324 pwname
= xstrdup(pw
->pw_name
);
1325 pwdir
= xstrdup(pw
->pw_dir
);
1326 if (gethostname(thishost
, sizeof(thishost
)) == -1)
1327 fatal("load_public_identity_files: gethostname: %s",
1329 for (; i
< options
.num_identity_files
; i
++) {
1330 cp
= tilde_expand_filename(options
.identity_files
[i
],
1332 filename
= percent_expand(cp
, "d", pwdir
,
1333 "u", pwname
, "l", thishost
, "h", host
,
1334 "r", options
.user
, (char *)NULL
);
1336 public = key_load_public(filename
, NULL
);
1337 debug("identity file %s type %d", filename
,
1338 public ? public->type
: -1);
1339 xfree(options
.identity_files
[i
]);
1340 options
.identity_files
[i
] = filename
;
1341 options
.identity_keys
[i
] = public;
1343 bzero(pwname
, strlen(pwname
));
1345 bzero(pwdir
, strlen(pwdir
));