1 /* $OpenBSD: ssh.c,v 1.324 2009/02/12 03:00:56 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Ssh client program. This program can be used to log into a remote machine.
7 * The software supports strong authentication, encryption, and forwarding
8 * of X11, TCP/IP, and authentication connections.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
19 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
69 #include <netinet/in.h>
70 #include <arpa/inet.h>
72 #include <openssl/evp.h>
73 #include <openssl/err.h>
74 #include "openbsd-compat/openssl-compat.h"
75 #include "openbsd-compat/sys-queue.h"
89 #include "pathnames.h"
91 #include "clientloop.h"
94 #include "sshconnect.h"
108 extern char *__progname
;
110 /* Flag indicating whether debug mode is on. May be set on the command line. */
113 /* Flag indicating whether a tty should be allocated */
116 int force_tty_flag
= 0;
118 /* don't exec a shell */
119 int no_shell_flag
= 0;
122 * Flag indicating that nothing should be read from stdin. This can be set
123 * on the command line.
125 int stdin_null_flag
= 0;
128 * Flag indicating that ssh should fork after authentication. This is useful
129 * so that the passphrase can be entered manually, and then ssh goes to the
132 int fork_after_authentication_flag
= 0;
135 * General data structure for command line options and options configurable
136 * in configuration files. See readconf.h.
140 /* optional user configfile */
144 * Name of the host we are connecting to. This is the name given on the
145 * command line, or the HostName specified for the user-supplied name in a
146 * configuration file.
150 /* socket address the host resolves to */
151 struct sockaddr_storage hostaddr
;
153 /* Private host keys. */
154 Sensitive sensitive_data
;
156 /* Original real UID. */
157 uid_t original_real_uid
;
158 uid_t original_effective_uid
;
160 /* command to be executed */
163 /* Should we execute a command or invoke a subsystem? */
164 int subsystem_flag
= 0;
166 /* # of replies received for global requests */
167 static int remote_forward_confirms_received
= 0;
169 /* pid of proxycommand child process */
170 pid_t proxy_command_pid
= 0;
173 extern int muxserver_sock
;
174 extern u_int muxclient_command
;
176 /* Prints a help message to the user. This function never returns. */
182 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
183 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
184 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
185 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
186 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
187 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
192 static int ssh_session(void);
193 static int ssh_session2(void);
194 static void load_public_identity_files(void);
196 /* from muxclient.c */
197 void muxclient(const char *);
198 void muxserver_listen(void);
201 * Main program for the ssh client.
204 main(int ac
, char **av
)
206 int i
, opt
, exit_status
, use_syslog
;
207 char *p
, *cp
, *line
, buf
[256];
210 int dummy
, timeout_ms
;
211 extern int optind
, optreset
;
216 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
219 __progname
= ssh_get_progname(av
[0]);
223 * Save the original real uid. It will be needed later (uid-swapping
224 * may clobber the real uid).
226 original_real_uid
= getuid();
227 original_effective_uid
= geteuid();
230 * Use uid-swapping to give up root privileges for the duration of
231 * option processing. We will re-instantiate the rights when we are
232 * ready to create the privileged port, and will permanently drop
233 * them when the port has been created (actually, when the connection
234 * has been made, as we may need to create the port several times).
238 #ifdef HAVE_SETRLIMIT
239 /* If we are installed setuid root be careful to not drop core. */
240 if (original_real_uid
!= original_effective_uid
) {
242 rlim
.rlim_cur
= rlim
.rlim_max
= 0;
243 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
244 fatal("setrlimit failed: %.100s", strerror(errno
));
248 pw
= getpwuid(original_real_uid
);
250 logit("You don't exist, go away!");
253 /* Take a copy of the returned structure. */
257 * Set our umask to something reasonable, as some files are created
258 * with the default umask. This will make them world-readable but
259 * writable only by the owner, which is ok for all files for which we
260 * don't set the modes explicitly.
265 * Initialize option structure to indicate that no values have been
268 initialize_options(&options
);
270 /* Parse command-line arguments. */
275 while ((opt
= getopt(ac
, av
, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
276 "ACD:F:I:KL:MNO:PR:S:TVw:XYy")) != -1) {
279 options
.protocol
= SSH_PROTO_1
;
282 options
.protocol
= SSH_PROTO_2
;
285 options
.address_family
= AF_INET
;
288 options
.address_family
= AF_INET6
;
294 fork_after_authentication_flag
= 1;
298 options
.forward_x11
= 0;
301 options
.forward_x11
= 1;
307 options
.forward_x11
= 1;
308 options
.forward_x11_trusted
= 1;
311 options
.gateway_ports
= 1;
314 if (strcmp(optarg
, "check") == 0)
315 muxclient_command
= SSHMUX_COMMAND_ALIVE_CHECK
;
316 else if (strcmp(optarg
, "exit") == 0)
317 muxclient_command
= SSHMUX_COMMAND_TERMINATE
;
319 fatal("Invalid multiplex command.");
321 case 'P': /* deprecated */
322 options
.use_privileged_port
= 0;
325 options
.forward_agent
= 0;
328 options
.forward_agent
= 1;
331 options
.gss_deleg_creds
= 0;
334 options
.gss_authentication
= 1;
335 options
.gss_deleg_creds
= 1;
338 if (stat(optarg
, &st
) < 0) {
339 fprintf(stderr
, "Warning: Identity file %s "
340 "not accessible: %s.\n", optarg
,
344 if (options
.num_identity_files
>=
345 SSH_MAX_IDENTITY_FILES
)
346 fatal("Too many identity files specified "
347 "(max %d)", SSH_MAX_IDENTITY_FILES
);
348 options
.identity_files
[options
.num_identity_files
++] =
353 options
.smartcard_device
= xstrdup(optarg
);
355 fprintf(stderr
, "no support for smartcards.\n");
364 if (debug_flag
== 0) {
366 options
.log_level
= SYSLOG_LEVEL_DEBUG1
;
368 if (options
.log_level
< SYSLOG_LEVEL_DEBUG3
)
374 fprintf(stderr
, "%s, %s\n",
375 SSH_RELEASE
, SSLeay_version(SSLEAY_VERSION
));
380 if (options
.tun_open
== -1)
381 options
.tun_open
= SSH_TUNMODE_DEFAULT
;
382 options
.tun_local
= a2tun(optarg
, &options
.tun_remote
);
383 if (options
.tun_local
== SSH_TUNID_ERR
) {
385 "Bad tun device '%s'\n", optarg
);
390 options
.log_level
= SYSLOG_LEVEL_QUIET
;
393 if (optarg
[0] == '^' && optarg
[2] == 0 &&
394 (u_char
) optarg
[1] >= 64 &&
395 (u_char
) optarg
[1] < 128)
396 options
.escape_char
= (u_char
) optarg
[1] & 31;
397 else if (strlen(optarg
) == 1)
398 options
.escape_char
= (u_char
) optarg
[0];
399 else if (strcmp(optarg
, "none") == 0)
400 options
.escape_char
= SSH_ESCAPECHAR_NONE
;
402 fprintf(stderr
, "Bad escape character '%s'.\n",
408 if (ciphers_valid(optarg
)) {
410 options
.ciphers
= xstrdup(optarg
);
411 options
.cipher
= SSH_CIPHER_INVALID
;
414 options
.cipher
= cipher_number(optarg
);
415 if (options
.cipher
== -1) {
417 "Unknown cipher type '%s'\n",
421 if (options
.cipher
== SSH_CIPHER_3DES
)
422 options
.ciphers
= "3des-cbc";
423 else if (options
.cipher
== SSH_CIPHER_BLOWFISH
)
424 options
.ciphers
= "blowfish-cbc";
426 options
.ciphers
= (char *)-1;
430 if (mac_valid(optarg
))
431 options
.macs
= xstrdup(optarg
);
433 fprintf(stderr
, "Unknown mac type '%s'\n",
439 if (options
.control_master
== SSHCTL_MASTER_YES
)
440 options
.control_master
= SSHCTL_MASTER_ASK
;
442 options
.control_master
= SSHCTL_MASTER_YES
;
445 options
.port
= a2port(optarg
);
446 if (options
.port
<= 0) {
447 fprintf(stderr
, "Bad port '%s'\n", optarg
);
452 options
.user
= optarg
;
456 if (parse_forward(&fwd
, optarg
, 0, 0))
457 add_local_forward(&options
, &fwd
);
460 "Bad local forwarding specification '%s'\n",
467 if (parse_forward(&fwd
, optarg
, 0, 1)) {
468 add_remote_forward(&options
, &fwd
);
471 "Bad remote forwarding specification "
478 if (parse_forward(&fwd
, optarg
, 1, 0)) {
479 add_local_forward(&options
, &fwd
);
482 "Bad dynamic forwarding specification "
489 options
.compression
= 1;
500 line
= xstrdup(optarg
);
501 if (process_config_line(&options
, host
? host
: "",
502 line
, "command-line", 0, &dummy
) != 0)
510 if (options
.control_path
!= NULL
)
511 free(options
.control_path
);
512 options
.control_path
= xstrdup(optarg
);
515 options
.bind_address
= optarg
;
528 if (ac
> 0 && !host
&& **av
!= '-') {
529 if (strrchr(*av
, '@')) {
531 cp
= strrchr(p
, '@');
532 if (cp
== NULL
|| cp
== p
)
540 optind
= optreset
= 1;
546 /* Check that we got a host name. */
550 SSLeay_add_all_algorithms();
551 ERR_load_crypto_strings();
553 /* Initialize the command to execute on remote host. */
554 buffer_init(&command
);
557 * Save the command to execute on the remote host in a buffer. There
558 * is no limit on the length of the command, except by the maximum
559 * packet size. Also sets the tty flag if there is no command.
562 /* No command specified - execute shell on a tty. */
564 if (subsystem_flag
) {
566 "You must specify a subsystem to invoke.\n");
570 /* A command has been specified. Store it into the buffer. */
571 for (i
= 0; i
< ac
; i
++) {
573 buffer_append(&command
, " ", 1);
574 buffer_append(&command
, av
[i
], strlen(av
[i
]));
578 /* Cannot fork to background if no command. */
579 if (fork_after_authentication_flag
&& buffer_len(&command
) == 0 &&
581 fatal("Cannot fork into background without a command "
584 /* Allocate a tty by default if no command specified. */
585 if (buffer_len(&command
) == 0)
591 /* Do not allocate a tty if stdin is not a tty. */
592 if ((!isatty(fileno(stdin
)) || stdin_null_flag
) && !force_tty_flag
) {
594 logit("Pseudo-terminal will not be allocated because "
595 "stdin is not a terminal.");
600 * Initialize "log" output. Since we are the client all output
601 * actually goes to stderr.
604 options
.log_level
== -1 ? SYSLOG_LEVEL_INFO
: options
.log_level
,
605 SYSLOG_FACILITY_USER
, !use_syslog
);
608 * Read per-user configuration file. Ignore the system wide config
609 * file if the user specifies a config file on the command line.
611 if (config
!= NULL
) {
612 if (!read_config_file(config
, host
, &options
, 0))
613 fatal("Can't open user config file %.100s: "
614 "%.100s", config
, strerror(errno
));
616 snprintf(buf
, sizeof buf
, "%.100s/%.100s", pw
->pw_dir
,
617 _PATH_SSH_USER_CONFFILE
);
618 (void)read_config_file(buf
, host
, &options
, 1);
620 /* Read systemwide configuration file after use config. */
621 (void)read_config_file(_PATH_HOST_CONFIG_FILE
, host
,
625 /* Fill configuration defaults. */
626 fill_default_options(&options
);
628 channel_set_af(options
.address_family
);
631 log_init(av
[0], options
.log_level
, SYSLOG_FACILITY_USER
, !use_syslog
);
635 if (options
.user
== NULL
)
636 options
.user
= xstrdup(pw
->pw_name
);
638 /* Get default port if port has not been set. */
639 if (options
.port
== 0) {
640 sp
= getservbyname(SSH_SERVICE_NAME
, "tcp");
641 options
.port
= sp
? ntohs(sp
->s_port
) : SSH_DEFAULT_PORT
;
644 if (options
.local_command
!= NULL
) {
645 char thishost
[NI_MAXHOST
];
647 if (gethostname(thishost
, sizeof(thishost
)) == -1)
648 fatal("gethostname: %s", strerror(errno
));
649 snprintf(buf
, sizeof(buf
), "%d", options
.port
);
650 debug3("expanding LocalCommand: %s", options
.local_command
);
651 cp
= options
.local_command
;
652 options
.local_command
= percent_expand(cp
, "d", pw
->pw_dir
,
653 "h", options
.hostname
? options
.hostname
: host
,
654 "l", thishost
, "n", host
, "r", options
.user
, "p", buf
,
655 "u", pw
->pw_name
, (char *)NULL
);
656 debug3("expanded LocalCommand: %s", options
.local_command
);
660 if (options
.hostname
!= NULL
)
661 host
= options
.hostname
;
663 /* Find canonic host name. */
664 if (strchr(host
, '.') == 0) {
665 struct addrinfo hints
;
666 struct addrinfo
*ai
= NULL
;
668 memset(&hints
, 0, sizeof(hints
));
669 hints
.ai_family
= options
.address_family
;
670 hints
.ai_flags
= AI_CANONNAME
;
671 hints
.ai_socktype
= SOCK_STREAM
;
672 errgai
= getaddrinfo(host
, NULL
, &hints
, &ai
);
674 if (ai
->ai_canonname
!= NULL
)
675 host
= xstrdup(ai
->ai_canonname
);
680 /* force lowercase for hostkey matching */
681 if (options
.host_key_alias
!= NULL
) {
682 for (p
= options
.host_key_alias
; *p
; p
++)
684 *p
= (char)tolower(*p
);
687 if (options
.proxy_command
!= NULL
&&
688 strcmp(options
.proxy_command
, "none") == 0) {
689 xfree(options
.proxy_command
);
690 options
.proxy_command
= NULL
;
692 if (options
.control_path
!= NULL
&&
693 strcmp(options
.control_path
, "none") == 0) {
694 xfree(options
.control_path
);
695 options
.control_path
= NULL
;
698 if (options
.control_path
!= NULL
) {
699 char thishost
[NI_MAXHOST
];
701 if (gethostname(thishost
, sizeof(thishost
)) == -1)
702 fatal("gethostname: %s", strerror(errno
));
703 snprintf(buf
, sizeof(buf
), "%d", options
.port
);
704 cp
= tilde_expand_filename(options
.control_path
,
706 xfree(options
.control_path
);
707 options
.control_path
= percent_expand(cp
, "p", buf
, "h", host
,
708 "r", options
.user
, "l", thishost
, (char *)NULL
);
711 if (muxclient_command
!= 0 && options
.control_path
== NULL
)
712 fatal("No ControlPath specified for \"-O\" command");
713 if (options
.control_path
!= NULL
)
714 muxclient(options
.control_path
);
716 timeout_ms
= options
.connection_timeout
* 1000;
718 /* Open a connection to the remote host. */
719 if (ssh_connect(host
, &hostaddr
, options
.port
,
720 options
.address_family
, options
.connection_attempts
, &timeout_ms
,
721 options
.tcp_keep_alive
,
723 options
.use_privileged_port
,
725 original_effective_uid
== 0 && options
.use_privileged_port
,
727 options
.proxy_command
) != 0)
731 debug3("timeout: %d ms remain after connect", timeout_ms
);
734 * If we successfully made the connection, load the host private key
735 * in case we will need it later for combined rsa-rhosts
736 * authentication. This must be done before releasing extra
737 * privileges, because the file is only readable by root.
738 * If we cannot access the private keys, load the public keys
739 * instead and try to execute the ssh-keysign helper instead.
741 sensitive_data
.nkeys
= 0;
742 sensitive_data
.keys
= NULL
;
743 sensitive_data
.external_keysign
= 0;
744 if (options
.rhosts_rsa_authentication
||
745 options
.hostbased_authentication
) {
746 sensitive_data
.nkeys
= 3;
747 sensitive_data
.keys
= xcalloc(sensitive_data
.nkeys
,
751 sensitive_data
.keys
[0] = key_load_private_type(KEY_RSA1
,
752 _PATH_HOST_KEY_FILE
, "", NULL
, NULL
);
753 sensitive_data
.keys
[1] = key_load_private_type(KEY_DSA
,
754 _PATH_HOST_DSA_KEY_FILE
, "", NULL
, NULL
);
755 sensitive_data
.keys
[2] = key_load_private_type(KEY_RSA
,
756 _PATH_HOST_RSA_KEY_FILE
, "", NULL
, NULL
);
759 if (options
.hostbased_authentication
== 1 &&
760 sensitive_data
.keys
[0] == NULL
&&
761 sensitive_data
.keys
[1] == NULL
&&
762 sensitive_data
.keys
[2] == NULL
) {
763 sensitive_data
.keys
[1] = key_load_public(
764 _PATH_HOST_DSA_KEY_FILE
, NULL
);
765 sensitive_data
.keys
[2] = key_load_public(
766 _PATH_HOST_RSA_KEY_FILE
, NULL
);
767 sensitive_data
.external_keysign
= 1;
771 * Get rid of any extra privileges that we may have. We will no
772 * longer need them. Also, extra privileges could make it very hard
773 * to read identity files and other non-world-readable files from the
774 * user's home directory if it happens to be on a NFS volume where
775 * root is mapped to nobody.
777 if (original_effective_uid
== 0) {
779 permanently_set_uid(pw
);
783 * Now that we are back to our own permissions, create ~/.ssh
784 * directory if it doesn't already exist.
786 snprintf(buf
, sizeof buf
, "%.100s%s%.100s", pw
->pw_dir
,
787 strcmp(pw
->pw_dir
, "/") ? "/" : "", _PATH_SSH_USER_DIR
);
788 if (stat(buf
, &st
) < 0)
789 if (mkdir(buf
, 0700) < 0)
790 error("Could not create directory '%.200s'.", buf
);
792 /* load options.identity_files */
793 load_public_identity_files();
795 /* Expand ~ in known host file names. */
797 options
.system_hostfile
=
798 tilde_expand_filename(options
.system_hostfile
, original_real_uid
);
799 options
.user_hostfile
=
800 tilde_expand_filename(options
.user_hostfile
, original_real_uid
);
801 options
.system_hostfile2
=
802 tilde_expand_filename(options
.system_hostfile2
, original_real_uid
);
803 options
.user_hostfile2
=
804 tilde_expand_filename(options
.user_hostfile2
, original_real_uid
);
806 signal(SIGPIPE
, SIG_IGN
); /* ignore SIGPIPE early */
808 /* Log into the remote system. Never returns if the login fails. */
809 ssh_login(&sensitive_data
, host
, (struct sockaddr
*)&hostaddr
,
812 /* We no longer need the private host keys. Clear them now. */
813 if (sensitive_data
.nkeys
!= 0) {
814 for (i
= 0; i
< sensitive_data
.nkeys
; i
++) {
815 if (sensitive_data
.keys
[i
] != NULL
) {
816 /* Destroys contents safely */
817 debug3("clear hostkey %d", i
);
818 key_free(sensitive_data
.keys
[i
]);
819 sensitive_data
.keys
[i
] = NULL
;
822 xfree(sensitive_data
.keys
);
824 for (i
= 0; i
< options
.num_identity_files
; i
++) {
825 if (options
.identity_files
[i
]) {
826 xfree(options
.identity_files
[i
]);
827 options
.identity_files
[i
] = NULL
;
829 if (options
.identity_keys
[i
]) {
830 key_free(options
.identity_keys
[i
]);
831 options
.identity_keys
[i
] = NULL
;
835 exit_status
= compat20
? ssh_session2() : ssh_session();
838 if (options
.control_path
!= NULL
&& muxserver_sock
!= -1)
839 unlink(options
.control_path
);
842 * Send SIGHUP to proxy command if used. We don't wait() in
843 * case it hangs and instead rely on init to reap the child
845 if (proxy_command_pid
> 1)
846 kill(proxy_command_pid
, SIGHUP
);
851 /* Callback for remote forward global requests */
853 ssh_confirm_remote_forward(int type
, u_int32_t seq
, void *ctxt
)
855 Forward
*rfwd
= (Forward
*)ctxt
;
857 /* XXX verbose() on failure? */
858 debug("remote forward %s for: listen %d, connect %s:%d",
859 type
== SSH2_MSG_REQUEST_SUCCESS
? "success" : "failure",
860 rfwd
->listen_port
, rfwd
->connect_host
, rfwd
->connect_port
);
861 if (type
== SSH2_MSG_REQUEST_SUCCESS
&& rfwd
->listen_port
== 0) {
862 logit("Allocated port %u for remote forward to %s:%d",
864 rfwd
->connect_host
, rfwd
->connect_port
);
867 if (type
== SSH2_MSG_REQUEST_FAILURE
) {
868 if (options
.exit_on_forward_failure
)
869 fatal("Error: remote port forwarding failed for "
870 "listen port %d", rfwd
->listen_port
);
872 logit("Warning: remote port forwarding failed for "
873 "listen port %d", rfwd
->listen_port
);
875 if (++remote_forward_confirms_received
== options
.num_remote_forwards
) {
876 debug("All remote forwarding requests processed");
877 if (fork_after_authentication_flag
) {
878 fork_after_authentication_flag
= 0;
879 if (daemon(1, 1) < 0)
880 fatal("daemon() failed: %.200s",
887 ssh_init_forwarding(void)
892 /* Initiate local TCP/IP port forwardings. */
893 for (i
= 0; i
< options
.num_local_forwards
; i
++) {
894 debug("Local connections to %.200s:%d forwarded to remote "
896 (options
.local_forwards
[i
].listen_host
== NULL
) ?
897 (options
.gateway_ports
? "*" : "LOCALHOST") :
898 options
.local_forwards
[i
].listen_host
,
899 options
.local_forwards
[i
].listen_port
,
900 options
.local_forwards
[i
].connect_host
,
901 options
.local_forwards
[i
].connect_port
);
902 success
+= channel_setup_local_fwd_listener(
903 options
.local_forwards
[i
].listen_host
,
904 options
.local_forwards
[i
].listen_port
,
905 options
.local_forwards
[i
].connect_host
,
906 options
.local_forwards
[i
].connect_port
,
907 options
.gateway_ports
);
909 if (i
> 0 && success
!= i
&& options
.exit_on_forward_failure
)
910 fatal("Could not request local forwarding.");
911 if (i
> 0 && success
== 0)
912 error("Could not request local forwarding.");
914 /* Initiate remote TCP/IP port forwardings. */
915 for (i
= 0; i
< options
.num_remote_forwards
; i
++) {
916 debug("Remote connections from %.200s:%d forwarded to "
917 "local address %.200s:%d",
918 (options
.remote_forwards
[i
].listen_host
== NULL
) ?
919 "LOCALHOST" : options
.remote_forwards
[i
].listen_host
,
920 options
.remote_forwards
[i
].listen_port
,
921 options
.remote_forwards
[i
].connect_host
,
922 options
.remote_forwards
[i
].connect_port
);
923 if (channel_request_remote_forwarding(
924 options
.remote_forwards
[i
].listen_host
,
925 options
.remote_forwards
[i
].listen_port
,
926 options
.remote_forwards
[i
].connect_host
,
927 options
.remote_forwards
[i
].connect_port
) < 0) {
928 if (options
.exit_on_forward_failure
)
929 fatal("Could not request remote forwarding.");
931 logit("Warning: Could not request remote "
934 client_register_global_confirm(ssh_confirm_remote_forward
,
935 &options
.remote_forwards
[i
]);
938 /* Initiate tunnel forwarding. */
939 if (options
.tun_open
!= SSH_TUNMODE_NO
) {
940 if (client_request_tun_fwd(options
.tun_open
,
941 options
.tun_local
, options
.tun_remote
) == -1) {
942 if (options
.exit_on_forward_failure
)
943 fatal("Could not request tunnel forwarding.");
945 error("Could not request tunnel forwarding.");
951 check_agent_present(void)
953 if (options
.forward_agent
) {
954 /* Clear agent forwarding if we don't have an agent. */
955 if (!ssh_agent_present())
956 options
.forward_agent
= 0;
970 /* Enable compression if requested. */
971 if (options
.compression
) {
972 debug("Requesting compression at level %d.",
973 options
.compression_level
);
975 if (options
.compression_level
< 1 ||
976 options
.compression_level
> 9)
977 fatal("Compression level must be from 1 (fast) to "
980 /* Send the request. */
981 packet_start(SSH_CMSG_REQUEST_COMPRESSION
);
982 packet_put_int(options
.compression_level
);
985 type
= packet_read();
986 if (type
== SSH_SMSG_SUCCESS
)
987 packet_start_compression(options
.compression_level
);
988 else if (type
== SSH_SMSG_FAILURE
)
989 logit("Warning: Remote host refused compression.");
991 packet_disconnect("Protocol error waiting for "
992 "compression response.");
994 /* Allocate a pseudo tty if appropriate. */
996 debug("Requesting pty.");
998 /* Start the packet. */
999 packet_start(SSH_CMSG_REQUEST_PTY
);
1001 /* Store TERM in the packet. There is no limit on the
1002 length of the string. */
1003 cp
= getenv("TERM");
1006 packet_put_cstring(cp
);
1008 /* Store window size in the packet. */
1009 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) < 0)
1010 memset(&ws
, 0, sizeof(ws
));
1011 packet_put_int((u_int
)ws
.ws_row
);
1012 packet_put_int((u_int
)ws
.ws_col
);
1013 packet_put_int((u_int
)ws
.ws_xpixel
);
1014 packet_put_int((u_int
)ws
.ws_ypixel
);
1016 /* Store tty modes in the packet. */
1017 tty_make_modes(fileno(stdin
), NULL
);
1019 /* Send the packet, and wait for it to leave. */
1021 packet_write_wait();
1023 /* Read response from the server. */
1024 type
= packet_read();
1025 if (type
== SSH_SMSG_SUCCESS
) {
1028 } else if (type
== SSH_SMSG_FAILURE
)
1029 logit("Warning: Remote host failed or refused to "
1030 "allocate a pseudo tty.");
1032 packet_disconnect("Protocol error waiting for pty "
1033 "request response.");
1035 /* Request X11 forwarding if enabled and DISPLAY is set. */
1036 display
= getenv("DISPLAY");
1037 if (options
.forward_x11
&& display
!= NULL
) {
1039 /* Get reasonable local authentication information. */
1040 client_x11_get_proto(display
, options
.xauth_location
,
1041 options
.forward_x11_trusted
, &proto
, &data
);
1042 /* Request forwarding with authentication spoofing. */
1043 debug("Requesting X11 forwarding with authentication "
1045 x11_request_forwarding_with_spoofing(0, display
, proto
, data
);
1047 /* Read response from the server. */
1048 type
= packet_read();
1049 if (type
== SSH_SMSG_SUCCESS
) {
1051 } else if (type
== SSH_SMSG_FAILURE
) {
1052 logit("Warning: Remote host denied X11 forwarding.");
1054 packet_disconnect("Protocol error waiting for X11 "
1058 /* Tell the packet module whether this is an interactive session. */
1059 packet_set_interactive(interactive
);
1061 /* Request authentication agent forwarding if appropriate. */
1062 check_agent_present();
1064 if (options
.forward_agent
) {
1065 debug("Requesting authentication agent forwarding.");
1066 auth_request_forwarding();
1068 /* Read response from the server. */
1069 type
= packet_read();
1071 if (type
!= SSH_SMSG_SUCCESS
)
1072 logit("Warning: Remote host denied authentication agent forwarding.");
1075 /* Initiate port forwardings. */
1076 ssh_init_forwarding();
1078 /* Execute a local command */
1079 if (options
.local_command
!= NULL
&&
1080 options
.permit_local_command
)
1081 ssh_local_cmd(options
.local_command
);
1084 * If requested and we are not interested in replies to remote
1085 * forwarding requests, then let ssh continue in the background.
1087 if (fork_after_authentication_flag
&&
1088 (!options
.exit_on_forward_failure
||
1089 options
.num_remote_forwards
== 0)) {
1090 fork_after_authentication_flag
= 0;
1091 if (daemon(1, 1) < 0)
1092 fatal("daemon() failed: %.200s", strerror(errno
));
1096 * If a command was specified on the command line, execute the
1097 * command now. Otherwise request the server to start a shell.
1099 if (buffer_len(&command
) > 0) {
1100 int len
= buffer_len(&command
);
1103 debug("Sending command: %.*s", len
,
1104 (u_char
*)buffer_ptr(&command
));
1105 packet_start(SSH_CMSG_EXEC_CMD
);
1106 packet_put_string(buffer_ptr(&command
), buffer_len(&command
));
1108 packet_write_wait();
1110 debug("Requesting shell.");
1111 packet_start(SSH_CMSG_EXEC_SHELL
);
1113 packet_write_wait();
1116 /* Enter the interactive session. */
1117 return client_loop(have_tty
, tty_flag
?
1118 options
.escape_char
: SSH_ESCAPECHAR_NONE
, 0);
1121 /* request pty/x11/agent/tcpfwd/shell for channel */
1123 ssh_session2_setup(int id
, void *arg
)
1125 extern char **environ
;
1126 const char *display
;
1127 int interactive
= tty_flag
;
1129 display
= getenv("DISPLAY");
1130 if (options
.forward_x11
&& display
!= NULL
) {
1132 /* Get reasonable local authentication information. */
1133 client_x11_get_proto(display
, options
.xauth_location
,
1134 options
.forward_x11_trusted
, &proto
, &data
);
1135 /* Request forwarding with authentication spoofing. */
1136 debug("Requesting X11 forwarding with authentication "
1138 x11_request_forwarding_with_spoofing(id
, display
, proto
, data
);
1140 /* XXX wait for reply */
1143 check_agent_present();
1144 if (options
.forward_agent
) {
1145 debug("Requesting authentication agent forwarding.");
1146 channel_request_start(id
, "auth-agent-req@openssh.com", 0);
1150 client_session2_setup(id
, tty_flag
, subsystem_flag
, getenv("TERM"),
1151 NULL
, fileno(stdin
), &command
, environ
);
1153 packet_set_interactive(interactive
);
1156 /* open new channel for a session */
1158 ssh_session2_open(void)
1161 int window
, packetmax
, in
, out
, err
;
1163 if (stdin_null_flag
) {
1164 in
= open(_PATH_DEVNULL
, O_RDONLY
);
1166 in
= dup(STDIN_FILENO
);
1168 out
= dup(STDOUT_FILENO
);
1169 err
= dup(STDERR_FILENO
);
1171 if (in
< 0 || out
< 0 || err
< 0)
1172 fatal("dup() in/out/err failed");
1174 /* enable nonblocking unless tty */
1182 window
= CHAN_SES_WINDOW_DEFAULT
;
1183 packetmax
= CHAN_SES_PACKET_DEFAULT
;
1189 "session", SSH_CHANNEL_OPENING
, in
, out
, err
,
1190 window
, packetmax
, CHAN_EXTENDED_WRITE
,
1191 "client-session", /*nonblock*/0);
1193 debug3("ssh_session2_open: channel_new: %d", c
->self
);
1195 channel_send_open(c
->self
);
1197 channel_register_open_confirm(c
->self
,
1198 ssh_session2_setup
, NULL
);
1208 /* XXX should be pre-session */
1209 ssh_init_forwarding();
1211 if (!no_shell_flag
|| (datafellows
& SSH_BUG_DUMMYCHAN
))
1212 id
= ssh_session2_open();
1214 /* If we don't expect to open a new session, then disallow it */
1215 if (options
.control_master
== SSHCTL_MASTER_NO
&&
1216 (datafellows
& SSH_NEW_OPENSSH
)) {
1217 debug("Requesting no-more-sessions@openssh.com");
1218 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
1219 packet_put_cstring("no-more-sessions@openssh.com");
1224 /* Execute a local command */
1225 if (options
.local_command
!= NULL
&&
1226 options
.permit_local_command
)
1227 ssh_local_cmd(options
.local_command
);
1229 /* Start listening for multiplex clients */
1232 /* If requested, let ssh continue in the background. */
1233 if (fork_after_authentication_flag
) {
1234 fork_after_authentication_flag
= 0;
1235 if (daemon(1, 1) < 0)
1236 fatal("daemon() failed: %.200s", strerror(errno
));
1239 return client_loop(tty_flag
, tty_flag
?
1240 options
.escape_char
: SSH_ESCAPECHAR_NONE
, id
);
1244 load_public_identity_files(void)
1246 char *filename
, *cp
, thishost
[NI_MAXHOST
];
1247 char *pwdir
= NULL
, *pwname
= NULL
;
1254 if (options
.smartcard_device
!= NULL
&&
1255 options
.num_identity_files
< SSH_MAX_IDENTITY_FILES
&&
1256 (keys
= sc_get_keys(options
.smartcard_device
, NULL
)) != NULL
) {
1258 for (i
= 0; keys
[i
] != NULL
; i
++) {
1260 memmove(&options
.identity_files
[1],
1261 &options
.identity_files
[0],
1262 sizeof(char *) * (SSH_MAX_IDENTITY_FILES
- 1));
1263 memmove(&options
.identity_keys
[1],
1264 &options
.identity_keys
[0],
1265 sizeof(Key
*) * (SSH_MAX_IDENTITY_FILES
- 1));
1266 options
.num_identity_files
++;
1267 options
.identity_keys
[0] = keys
[i
];
1268 options
.identity_files
[0] = sc_get_key_label(keys
[i
]);
1270 if (options
.num_identity_files
> SSH_MAX_IDENTITY_FILES
)
1271 options
.num_identity_files
= SSH_MAX_IDENTITY_FILES
;
1275 #endif /* SMARTCARD */
1276 if ((pw
= getpwuid(original_real_uid
)) == NULL
)
1277 fatal("load_public_identity_files: getpwuid failed");
1278 pwname
= xstrdup(pw
->pw_name
);
1279 pwdir
= xstrdup(pw
->pw_dir
);
1280 if (gethostname(thishost
, sizeof(thishost
)) == -1)
1281 fatal("load_public_identity_files: gethostname: %s",
1283 for (; i
< options
.num_identity_files
; i
++) {
1284 cp
= tilde_expand_filename(options
.identity_files
[i
],
1286 filename
= percent_expand(cp
, "d", pwdir
,
1287 "u", pwname
, "l", thishost
, "h", host
,
1288 "r", options
.user
, (char *)NULL
);
1290 public = key_load_public(filename
, NULL
);
1291 debug("identity file %s type %d", filename
,
1292 public ? public->type
: -1);
1293 xfree(options
.identity_files
[i
]);
1294 options
.identity_files
[i
] = filename
;
1295 options
.identity_keys
[i
] = public;
1297 bzero(pwname
, strlen(pwname
));
1299 bzero(pwdir
, strlen(pwdir
));