1 /* $OpenBSD: ssh.c,v 1.314 2008/06/10 22:15:23 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. This can be set on the command line. */
113 /* Flag indicating whether a tty should be allocated */
116 int force_tty_flag
= 0;
118 /* don't exec a shell */
119 int no_shell_flag
= 0;
122 * Flag indicating that nothing should be read from stdin. This can be set
123 * on the command line.
125 int stdin_null_flag
= 0;
128 * Flag indicating that ssh should fork after authentication. This is useful
129 * so that the passphrase can be entered manually, and then ssh goes to the
132 int fork_after_authentication_flag
= 0;
135 * General data structure for command line options and options configurable
136 * in configuration files. See readconf.h.
140 /* optional user configfile */
144 * Name of the host we are connecting to. This is the name given on the
145 * command line, or the HostName specified for the user-supplied name in a
146 * configuration file.
150 /* socket address the host resolves to */
151 struct sockaddr_storage hostaddr
;
153 /* Private host keys. */
154 Sensitive sensitive_data
;
156 /* Original real UID. */
157 uid_t original_real_uid
;
158 uid_t original_effective_uid
;
160 /* command to be executed */
163 /* Should we execute a command or invoke a subsystem? */
164 int subsystem_flag
= 0;
166 /* # of replies received for global requests */
167 static int client_global_request_id
= 0;
169 /* pid of proxycommand child process */
170 pid_t proxy_command_pid
= 0;
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 [-1246AaCfgKkMNnqsTtVvXxY] [-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
;
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.
264 /* Initialize option structure to indicate that no values have been set. */
265 initialize_options(&options
);
267 /* Parse command-line arguments. */
271 while ((opt
= getopt(ac
, av
,
272 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:KL:MNO:PR:S:TVw:XY")) != -1) {
275 options
.protocol
= SSH_PROTO_1
;
278 options
.protocol
= SSH_PROTO_2
;
281 options
.address_family
= AF_INET
;
284 options
.address_family
= AF_INET6
;
290 fork_after_authentication_flag
= 1;
294 options
.forward_x11
= 0;
297 options
.forward_x11
= 1;
300 options
.forward_x11
= 1;
301 options
.forward_x11_trusted
= 1;
304 options
.gateway_ports
= 1;
307 if (strcmp(optarg
, "check") == 0)
308 muxclient_command
= SSHMUX_COMMAND_ALIVE_CHECK
;
309 else if (strcmp(optarg
, "exit") == 0)
310 muxclient_command
= SSHMUX_COMMAND_TERMINATE
;
312 fatal("Invalid multiplex command.");
314 case 'P': /* deprecated */
315 options
.use_privileged_port
= 0;
318 options
.forward_agent
= 0;
321 options
.forward_agent
= 1;
324 options
.gss_deleg_creds
= 0;
327 options
.gss_authentication
= 1;
328 options
.gss_deleg_creds
= 1;
331 if (stat(optarg
, &st
) < 0) {
332 fprintf(stderr
, "Warning: Identity file %s "
333 "not accessible: %s.\n", optarg
,
337 if (options
.num_identity_files
>=
338 SSH_MAX_IDENTITY_FILES
)
339 fatal("Too many identity files specified "
340 "(max %d)", SSH_MAX_IDENTITY_FILES
);
341 options
.identity_files
[options
.num_identity_files
++] =
346 options
.smartcard_device
= xstrdup(optarg
);
348 fprintf(stderr
, "no support for smartcards.\n");
357 if (debug_flag
== 0) {
359 options
.log_level
= SYSLOG_LEVEL_DEBUG1
;
361 if (options
.log_level
< SYSLOG_LEVEL_DEBUG3
)
367 fprintf(stderr
, "%s, %s\n",
368 SSH_RELEASE
, SSLeay_version(SSLEAY_VERSION
));
373 if (options
.tun_open
== -1)
374 options
.tun_open
= SSH_TUNMODE_DEFAULT
;
375 options
.tun_local
= a2tun(optarg
, &options
.tun_remote
);
376 if (options
.tun_local
== SSH_TUNID_ERR
) {
377 fprintf(stderr
, "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
))
449 add_local_forward(&options
, &fwd
);
452 "Bad local forwarding specification '%s'\n",
459 if (parse_forward(&fwd
, optarg
)) {
460 add_remote_forward(&options
, &fwd
);
463 "Bad remote forwarding specification "
470 cp
= p
= xstrdup(optarg
);
471 memset(&fwd
, '\0', sizeof(fwd
));
472 fwd
.connect_host
= "socks";
473 if ((fwd
.listen_host
= hpdelim(&cp
)) == NULL
) {
474 fprintf(stderr
, "Bad dynamic forwarding "
475 "specification '%.100s'\n", optarg
);
479 fwd
.listen_port
= a2port(cp
);
480 fwd
.listen_host
= cleanhostname(fwd
.listen_host
);
482 fwd
.listen_port
= a2port(fwd
.listen_host
);
483 fwd
.listen_host
= NULL
;
486 if (fwd
.listen_port
== 0) {
487 fprintf(stderr
, "Bad dynamic port '%s'\n",
491 add_local_forward(&options
, &fwd
);
496 options
.compression
= 1;
507 line
= xstrdup(optarg
);
508 if (process_config_line(&options
, host
? host
: "",
509 line
, "command-line", 0, &dummy
) != 0)
517 if (options
.control_path
!= NULL
)
518 free(options
.control_path
);
519 options
.control_path
= xstrdup(optarg
);
522 options
.bind_address
= optarg
;
535 if (ac
> 0 && !host
&& **av
!= '-') {
536 if (strrchr(*av
, '@')) {
538 cp
= strrchr(p
, '@');
539 if (cp
== NULL
|| cp
== p
)
547 optind
= optreset
= 1;
553 /* Check that we got a host name. */
557 SSLeay_add_all_algorithms();
558 ERR_load_crypto_strings();
560 /* Initialize the command to execute on remote host. */
561 buffer_init(&command
);
564 * Save the command to execute on the remote host in a buffer. There
565 * is no limit on the length of the command, except by the maximum
566 * packet size. Also sets the tty flag if there is no command.
569 /* No command specified - execute shell on a tty. */
571 if (subsystem_flag
) {
573 "You must specify a subsystem to invoke.\n");
577 /* A command has been specified. Store it into the buffer. */
578 for (i
= 0; i
< ac
; i
++) {
580 buffer_append(&command
, " ", 1);
581 buffer_append(&command
, av
[i
], strlen(av
[i
]));
585 /* Cannot fork to background if no command. */
586 if (fork_after_authentication_flag
&& buffer_len(&command
) == 0 && !no_shell_flag
)
587 fatal("Cannot fork into background without a command to execute.");
589 /* Allocate a tty by default if no command specified. */
590 if (buffer_len(&command
) == 0)
596 /* Do not allocate a tty if stdin is not a tty. */
597 if ((!isatty(fileno(stdin
)) || stdin_null_flag
) && !force_tty_flag
) {
599 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
604 * Initialize "log" output. Since we are the client all output
605 * actually goes to stderr.
607 log_init(av
[0], options
.log_level
== -1 ? SYSLOG_LEVEL_INFO
: options
.log_level
,
608 SYSLOG_FACILITY_USER
, 1);
611 * Read per-user configuration file. Ignore the system wide config
612 * file if the user specifies a config file on the command line.
614 if (config
!= NULL
) {
615 if (!read_config_file(config
, host
, &options
, 0))
616 fatal("Can't open user config file %.100s: "
617 "%.100s", config
, strerror(errno
));
619 snprintf(buf
, sizeof buf
, "%.100s/%.100s", pw
->pw_dir
,
620 _PATH_SSH_USER_CONFFILE
);
621 (void)read_config_file(buf
, host
, &options
, 1);
623 /* Read systemwide configuration file after use config. */
624 (void)read_config_file(_PATH_HOST_CONFIG_FILE
, host
,
628 /* Fill configuration defaults. */
629 fill_default_options(&options
);
631 channel_set_af(options
.address_family
);
634 log_init(av
[0], options
.log_level
, SYSLOG_FACILITY_USER
, 1);
638 if (options
.user
== NULL
)
639 options
.user
= xstrdup(pw
->pw_name
);
641 if (options
.hostname
!= NULL
)
642 host
= options
.hostname
;
644 /* force lowercase for hostkey matching */
645 if (options
.host_key_alias
!= NULL
) {
646 for (p
= options
.host_key_alias
; *p
; p
++)
648 *p
= (char)tolower(*p
);
651 /* Get default port if port has not been set. */
652 if (options
.port
== 0) {
653 sp
= getservbyname(SSH_SERVICE_NAME
, "tcp");
654 options
.port
= sp
? ntohs(sp
->s_port
) : SSH_DEFAULT_PORT
;
657 if (options
.proxy_command
!= NULL
&&
658 strcmp(options
.proxy_command
, "none") == 0) {
659 xfree(options
.proxy_command
);
660 options
.proxy_command
= NULL
;
662 if (options
.control_path
!= NULL
&&
663 strcmp(options
.control_path
, "none") == 0) {
664 xfree(options
.control_path
);
665 options
.control_path
= NULL
;
668 if (options
.control_path
!= NULL
) {
669 char thishost
[NI_MAXHOST
];
671 if (gethostname(thishost
, sizeof(thishost
)) == -1)
672 fatal("gethostname: %s", strerror(errno
));
673 snprintf(buf
, sizeof(buf
), "%d", options
.port
);
674 cp
= tilde_expand_filename(options
.control_path
,
676 xfree(options
.control_path
);
677 options
.control_path
= percent_expand(cp
, "p", buf
, "h", host
,
678 "r", options
.user
, "l", thishost
, (char *)NULL
);
681 if (muxclient_command
!= 0 && options
.control_path
== NULL
)
682 fatal("No ControlPath specified for \"-O\" command");
683 if (options
.control_path
!= NULL
)
684 muxclient(options
.control_path
);
686 timeout_ms
= options
.connection_timeout
* 1000;
688 /* Open a connection to the remote host. */
689 if (ssh_connect(host
, &hostaddr
, options
.port
,
690 options
.address_family
, options
.connection_attempts
, &timeout_ms
,
691 options
.tcp_keep_alive
,
693 options
.use_privileged_port
,
695 original_effective_uid
== 0 && options
.use_privileged_port
,
697 options
.proxy_command
) != 0)
701 debug3("timeout: %d ms remain after connect", timeout_ms
);
704 * If we successfully made the connection, load the host private key
705 * in case we will need it later for combined rsa-rhosts
706 * authentication. This must be done before releasing extra
707 * privileges, because the file is only readable by root.
708 * If we cannot access the private keys, load the public keys
709 * instead and try to execute the ssh-keysign helper instead.
711 sensitive_data
.nkeys
= 0;
712 sensitive_data
.keys
= NULL
;
713 sensitive_data
.external_keysign
= 0;
714 if (options
.rhosts_rsa_authentication
||
715 options
.hostbased_authentication
) {
716 sensitive_data
.nkeys
= 3;
717 sensitive_data
.keys
= xcalloc(sensitive_data
.nkeys
,
721 sensitive_data
.keys
[0] = key_load_private_type(KEY_RSA1
,
722 _PATH_HOST_KEY_FILE
, "", NULL
, NULL
);
723 sensitive_data
.keys
[1] = key_load_private_type(KEY_DSA
,
724 _PATH_HOST_DSA_KEY_FILE
, "", NULL
, NULL
);
725 sensitive_data
.keys
[2] = key_load_private_type(KEY_RSA
,
726 _PATH_HOST_RSA_KEY_FILE
, "", NULL
, NULL
);
729 if (options
.hostbased_authentication
== 1 &&
730 sensitive_data
.keys
[0] == NULL
&&
731 sensitive_data
.keys
[1] == NULL
&&
732 sensitive_data
.keys
[2] == NULL
) {
733 sensitive_data
.keys
[1] = key_load_public(
734 _PATH_HOST_DSA_KEY_FILE
, NULL
);
735 sensitive_data
.keys
[2] = key_load_public(
736 _PATH_HOST_RSA_KEY_FILE
, NULL
);
737 sensitive_data
.external_keysign
= 1;
741 * Get rid of any extra privileges that we may have. We will no
742 * longer need them. Also, extra privileges could make it very hard
743 * to read identity files and other non-world-readable files from the
744 * user's home directory if it happens to be on a NFS volume where
745 * root is mapped to nobody.
747 if (original_effective_uid
== 0) {
749 permanently_set_uid(pw
);
753 * Now that we are back to our own permissions, create ~/.ssh
754 * directory if it doesn't already exist.
756 snprintf(buf
, sizeof buf
, "%.100s%s%.100s", pw
->pw_dir
, strcmp(pw
->pw_dir
, "/") ? "/" : "", _PATH_SSH_USER_DIR
);
757 if (stat(buf
, &st
) < 0)
758 if (mkdir(buf
, 0700) < 0)
759 error("Could not create directory '%.200s'.", buf
);
761 /* load options.identity_files */
762 load_public_identity_files();
764 /* Expand ~ in known host file names. */
766 options
.system_hostfile
=
767 tilde_expand_filename(options
.system_hostfile
, original_real_uid
);
768 options
.user_hostfile
=
769 tilde_expand_filename(options
.user_hostfile
, original_real_uid
);
770 options
.system_hostfile2
=
771 tilde_expand_filename(options
.system_hostfile2
, original_real_uid
);
772 options
.user_hostfile2
=
773 tilde_expand_filename(options
.user_hostfile2
, original_real_uid
);
775 signal(SIGPIPE
, SIG_IGN
); /* ignore SIGPIPE early */
777 /* Log into the remote system. This never returns if the login fails. */
778 ssh_login(&sensitive_data
, host
, (struct sockaddr
*)&hostaddr
,
781 /* We no longer need the private host keys. Clear them now. */
782 if (sensitive_data
.nkeys
!= 0) {
783 for (i
= 0; i
< sensitive_data
.nkeys
; i
++) {
784 if (sensitive_data
.keys
[i
] != NULL
) {
785 /* Destroys contents safely */
786 debug3("clear hostkey %d", i
);
787 key_free(sensitive_data
.keys
[i
]);
788 sensitive_data
.keys
[i
] = NULL
;
791 xfree(sensitive_data
.keys
);
793 for (i
= 0; i
< options
.num_identity_files
; i
++) {
794 if (options
.identity_files
[i
]) {
795 xfree(options
.identity_files
[i
]);
796 options
.identity_files
[i
] = NULL
;
798 if (options
.identity_keys
[i
]) {
799 key_free(options
.identity_keys
[i
]);
800 options
.identity_keys
[i
] = NULL
;
804 exit_status
= compat20
? ssh_session2() : ssh_session();
807 if (options
.control_path
!= NULL
&& muxserver_sock
!= -1)
808 unlink(options
.control_path
);
811 * Send SIGHUP to proxy command if used. We don't wait() in
812 * case it hangs and instead rely on init to reap the child
814 if (proxy_command_pid
> 1)
815 kill(proxy_command_pid
, SIGHUP
);
821 ssh_init_forwarding(void)
826 /* Initiate local TCP/IP port forwardings. */
827 for (i
= 0; i
< options
.num_local_forwards
; i
++) {
828 debug("Local connections to %.200s:%d forwarded to remote "
830 (options
.local_forwards
[i
].listen_host
== NULL
) ?
831 (options
.gateway_ports
? "*" : "LOCALHOST") :
832 options
.local_forwards
[i
].listen_host
,
833 options
.local_forwards
[i
].listen_port
,
834 options
.local_forwards
[i
].connect_host
,
835 options
.local_forwards
[i
].connect_port
);
836 success
+= channel_setup_local_fwd_listener(
837 options
.local_forwards
[i
].listen_host
,
838 options
.local_forwards
[i
].listen_port
,
839 options
.local_forwards
[i
].connect_host
,
840 options
.local_forwards
[i
].connect_port
,
841 options
.gateway_ports
);
843 if (i
> 0 && success
!= i
&& options
.exit_on_forward_failure
)
844 fatal("Could not request local forwarding.");
845 if (i
> 0 && success
== 0)
846 error("Could not request local forwarding.");
848 /* Initiate remote TCP/IP port forwardings. */
849 for (i
= 0; i
< options
.num_remote_forwards
; i
++) {
850 debug("Remote connections from %.200s:%d forwarded to "
851 "local address %.200s:%d",
852 (options
.remote_forwards
[i
].listen_host
== NULL
) ?
853 "LOCALHOST" : options
.remote_forwards
[i
].listen_host
,
854 options
.remote_forwards
[i
].listen_port
,
855 options
.remote_forwards
[i
].connect_host
,
856 options
.remote_forwards
[i
].connect_port
);
857 if (channel_request_remote_forwarding(
858 options
.remote_forwards
[i
].listen_host
,
859 options
.remote_forwards
[i
].listen_port
,
860 options
.remote_forwards
[i
].connect_host
,
861 options
.remote_forwards
[i
].connect_port
) < 0) {
862 if (options
.exit_on_forward_failure
)
863 fatal("Could not request remote forwarding.");
865 logit("Warning: Could not request remote "
870 /* Initiate tunnel forwarding. */
871 if (options
.tun_open
!= SSH_TUNMODE_NO
) {
872 if (client_request_tun_fwd(options
.tun_open
,
873 options
.tun_local
, options
.tun_remote
) == -1) {
874 if (options
.exit_on_forward_failure
)
875 fatal("Could not request tunnel forwarding.");
877 error("Could not request tunnel forwarding.");
883 check_agent_present(void)
885 if (options
.forward_agent
) {
886 /* Clear agent forwarding if we don't have an agent. */
887 if (!ssh_agent_present())
888 options
.forward_agent
= 0;
902 /* Enable compression if requested. */
903 if (options
.compression
) {
904 debug("Requesting compression at level %d.", options
.compression_level
);
906 if (options
.compression_level
< 1 || options
.compression_level
> 9)
907 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
909 /* Send the request. */
910 packet_start(SSH_CMSG_REQUEST_COMPRESSION
);
911 packet_put_int(options
.compression_level
);
914 type
= packet_read();
915 if (type
== SSH_SMSG_SUCCESS
)
916 packet_start_compression(options
.compression_level
);
917 else if (type
== SSH_SMSG_FAILURE
)
918 logit("Warning: Remote host refused compression.");
920 packet_disconnect("Protocol error waiting for compression response.");
922 /* Allocate a pseudo tty if appropriate. */
924 debug("Requesting pty.");
926 /* Start the packet. */
927 packet_start(SSH_CMSG_REQUEST_PTY
);
929 /* Store TERM in the packet. There is no limit on the
930 length of the string. */
934 packet_put_cstring(cp
);
936 /* Store window size in the packet. */
937 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) < 0)
938 memset(&ws
, 0, sizeof(ws
));
939 packet_put_int((u_int
)ws
.ws_row
);
940 packet_put_int((u_int
)ws
.ws_col
);
941 packet_put_int((u_int
)ws
.ws_xpixel
);
942 packet_put_int((u_int
)ws
.ws_ypixel
);
944 /* Store tty modes in the packet. */
945 tty_make_modes(fileno(stdin
), NULL
);
947 /* Send the packet, and wait for it to leave. */
951 /* Read response from the server. */
952 type
= packet_read();
953 if (type
== SSH_SMSG_SUCCESS
) {
956 } else if (type
== SSH_SMSG_FAILURE
)
957 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
959 packet_disconnect("Protocol error waiting for pty request response.");
961 /* Request X11 forwarding if enabled and DISPLAY is set. */
962 display
= getenv("DISPLAY");
963 if (options
.forward_x11
&& display
!= NULL
) {
965 /* Get reasonable local authentication information. */
966 client_x11_get_proto(display
, options
.xauth_location
,
967 options
.forward_x11_trusted
, &proto
, &data
);
968 /* Request forwarding with authentication spoofing. */
969 debug("Requesting X11 forwarding with authentication spoofing.");
970 x11_request_forwarding_with_spoofing(0, display
, proto
, data
);
972 /* Read response from the server. */
973 type
= packet_read();
974 if (type
== SSH_SMSG_SUCCESS
) {
976 } else if (type
== SSH_SMSG_FAILURE
) {
977 logit("Warning: Remote host denied X11 forwarding.");
979 packet_disconnect("Protocol error waiting for X11 forwarding");
982 /* Tell the packet module whether this is an interactive session. */
983 packet_set_interactive(interactive
);
985 /* Request authentication agent forwarding if appropriate. */
986 check_agent_present();
988 if (options
.forward_agent
) {
989 debug("Requesting authentication agent forwarding.");
990 auth_request_forwarding();
992 /* Read response from the server. */
993 type
= packet_read();
995 if (type
!= SSH_SMSG_SUCCESS
)
996 logit("Warning: Remote host denied authentication agent forwarding.");
999 /* Initiate port forwardings. */
1000 ssh_init_forwarding();
1002 /* Execute a local command */
1003 if (options
.local_command
!= NULL
&&
1004 options
.permit_local_command
)
1005 ssh_local_cmd(options
.local_command
);
1007 /* If requested, let ssh continue in the background. */
1008 if (fork_after_authentication_flag
)
1009 if (daemon(1, 1) < 0)
1010 fatal("daemon() failed: %.200s", strerror(errno
));
1013 * If a command was specified on the command line, execute the
1014 * command now. Otherwise request the server to start a shell.
1016 if (buffer_len(&command
) > 0) {
1017 int len
= buffer_len(&command
);
1020 debug("Sending command: %.*s", len
, (u_char
*)buffer_ptr(&command
));
1021 packet_start(SSH_CMSG_EXEC_CMD
);
1022 packet_put_string(buffer_ptr(&command
), buffer_len(&command
));
1024 packet_write_wait();
1026 debug("Requesting shell.");
1027 packet_start(SSH_CMSG_EXEC_SHELL
);
1029 packet_write_wait();
1032 /* Enter the interactive session. */
1033 return client_loop(have_tty
, tty_flag
?
1034 options
.escape_char
: SSH_ESCAPECHAR_NONE
, 0);
1038 client_global_request_reply_fwd(int type
, u_int32_t seq
, void *ctxt
)
1042 i
= client_global_request_id
++;
1043 if (i
>= options
.num_remote_forwards
)
1045 debug("remote forward %s for: listen %d, connect %s:%d",
1046 type
== SSH2_MSG_REQUEST_SUCCESS
? "success" : "failure",
1047 options
.remote_forwards
[i
].listen_port
,
1048 options
.remote_forwards
[i
].connect_host
,
1049 options
.remote_forwards
[i
].connect_port
);
1050 if (type
== SSH2_MSG_REQUEST_FAILURE
) {
1051 if (options
.exit_on_forward_failure
)
1052 fatal("Error: remote port forwarding failed for "
1054 options
.remote_forwards
[i
].listen_port
);
1056 logit("Warning: remote port forwarding failed for "
1058 options
.remote_forwards
[i
].listen_port
);
1062 /* request pty/x11/agent/tcpfwd/shell for channel */
1064 ssh_session2_setup(int id
, void *arg
)
1066 extern char **environ
;
1067 const char *display
;
1068 int interactive
= tty_flag
;
1070 display
= getenv("DISPLAY");
1071 if (options
.forward_x11
&& display
!= NULL
) {
1073 /* Get reasonable local authentication information. */
1074 client_x11_get_proto(display
, options
.xauth_location
,
1075 options
.forward_x11_trusted
, &proto
, &data
);
1076 /* Request forwarding with authentication spoofing. */
1077 debug("Requesting X11 forwarding with authentication spoofing.");
1078 x11_request_forwarding_with_spoofing(id
, display
, proto
, data
);
1080 /* XXX wait for reply */
1083 check_agent_present();
1084 if (options
.forward_agent
) {
1085 debug("Requesting authentication agent forwarding.");
1086 channel_request_start(id
, "auth-agent-req@openssh.com", 0);
1090 client_session2_setup(id
, tty_flag
, subsystem_flag
, getenv("TERM"),
1091 NULL
, fileno(stdin
), &command
, environ
);
1093 packet_set_interactive(interactive
);
1096 /* open new channel for a session */
1098 ssh_session2_open(void)
1101 int window
, packetmax
, in
, out
, err
;
1103 if (stdin_null_flag
) {
1104 in
= open(_PATH_DEVNULL
, O_RDONLY
);
1106 in
= dup(STDIN_FILENO
);
1108 out
= dup(STDOUT_FILENO
);
1109 err
= dup(STDERR_FILENO
);
1111 if (in
< 0 || out
< 0 || err
< 0)
1112 fatal("dup() in/out/err failed");
1114 /* enable nonblocking unless tty */
1122 window
= CHAN_SES_WINDOW_DEFAULT
;
1123 packetmax
= CHAN_SES_PACKET_DEFAULT
;
1129 "session", SSH_CHANNEL_OPENING
, in
, out
, err
,
1130 window
, packetmax
, CHAN_EXTENDED_WRITE
,
1131 "client-session", /*nonblock*/0);
1133 debug3("ssh_session2_open: channel_new: %d", c
->self
);
1135 channel_send_open(c
->self
);
1137 channel_register_open_confirm(c
->self
,
1138 ssh_session2_setup
, NULL
);
1148 /* XXX should be pre-session */
1149 ssh_init_forwarding();
1151 if (!no_shell_flag
|| (datafellows
& SSH_BUG_DUMMYCHAN
))
1152 id
= ssh_session2_open();
1154 /* If we don't expect to open a new session, then disallow it */
1155 if (options
.control_master
== SSHCTL_MASTER_NO
) {
1156 debug("Requesting no-more-sessions@openssh.com");
1157 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
1158 packet_put_cstring("no-more-sessions@openssh.com");
1163 /* Execute a local command */
1164 if (options
.local_command
!= NULL
&&
1165 options
.permit_local_command
)
1166 ssh_local_cmd(options
.local_command
);
1168 /* Start listening for multiplex clients */
1171 /* If requested, let ssh continue in the background. */
1172 if (fork_after_authentication_flag
)
1173 if (daemon(1, 1) < 0)
1174 fatal("daemon() failed: %.200s", strerror(errno
));
1176 return client_loop(tty_flag
, tty_flag
?
1177 options
.escape_char
: SSH_ESCAPECHAR_NONE
, id
);
1181 load_public_identity_files(void)
1183 char *filename
, *cp
, thishost
[NI_MAXHOST
];
1184 char *pwdir
= NULL
, *pwname
= NULL
;
1191 if (options
.smartcard_device
!= NULL
&&
1192 options
.num_identity_files
< SSH_MAX_IDENTITY_FILES
&&
1193 (keys
= sc_get_keys(options
.smartcard_device
, NULL
)) != NULL
) {
1195 for (i
= 0; keys
[i
] != NULL
; i
++) {
1197 memmove(&options
.identity_files
[1], &options
.identity_files
[0],
1198 sizeof(char *) * (SSH_MAX_IDENTITY_FILES
- 1));
1199 memmove(&options
.identity_keys
[1], &options
.identity_keys
[0],
1200 sizeof(Key
*) * (SSH_MAX_IDENTITY_FILES
- 1));
1201 options
.num_identity_files
++;
1202 options
.identity_keys
[0] = keys
[i
];
1203 options
.identity_files
[0] = sc_get_key_label(keys
[i
]);
1205 if (options
.num_identity_files
> SSH_MAX_IDENTITY_FILES
)
1206 options
.num_identity_files
= SSH_MAX_IDENTITY_FILES
;
1210 #endif /* SMARTCARD */
1211 if ((pw
= getpwuid(original_real_uid
)) == NULL
)
1212 fatal("load_public_identity_files: getpwuid failed");
1213 pwname
= xstrdup(pw
->pw_name
);
1214 pwdir
= xstrdup(pw
->pw_dir
);
1215 if (gethostname(thishost
, sizeof(thishost
)) == -1)
1216 fatal("load_public_identity_files: gethostname: %s",
1218 for (; i
< options
.num_identity_files
; i
++) {
1219 cp
= tilde_expand_filename(options
.identity_files
[i
],
1221 filename
= percent_expand(cp
, "d", pwdir
,
1222 "u", pwname
, "l", thishost
, "h", host
,
1223 "r", options
.user
, (char *)NULL
);
1225 public = key_load_public(filename
, NULL
);
1226 debug("identity file %s type %d", filename
,
1227 public ? public->type
: -1);
1228 xfree(options
.identity_files
[i
]);
1229 options
.identity_files
[i
] = filename
;
1230 options
.identity_keys
[i
] = public;
1232 bzero(pwname
, strlen(pwname
));
1234 bzero(pwdir
, strlen(pwdir
));