1 /* $OpenBSD: ssh.c,v 1.316 2008/06/12 04:24:06 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 [-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.
265 * Initialize option structure to indicate that no values have been
268 initialize_options(&options);
270 /* Parse command-line arguments. */
274 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
275 "ACD:F:I:KL:MNO:PR:S:TVw:XY")) != -1) {
278 options.protocol = SSH_PROTO_1;
281 options.protocol = SSH_PROTO_2;
284 options.address_family = AF_INET;
287 options.address_family = AF_INET6;
293 fork_after_authentication_flag = 1;
297 options.forward_x11 = 0;
300 options.forward_x11 = 1;
303 options.forward_x11 = 1;
304 options.forward_x11_trusted = 1;
307 options.gateway_ports = 1;
310 if (strcmp(optarg, "check") == 0)
311 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
312 else if (strcmp(optarg, "exit") == 0)
313 muxclient_command = SSHMUX_COMMAND_TERMINATE;
315 fatal("Invalid multiplex command.");
317 case 'P': /* deprecated */
318 options.use_privileged_port = 0;
321 options.forward_agent = 0;
324 options.forward_agent = 1;
327 options.gss_deleg_creds = 0;
330 options.gss_authentication = 1;
331 options.gss_deleg_creds = 1;
334 if (stat(optarg, &st) < 0) {
335 fprintf(stderr, "Warning: Identity file %s "
336 "not accessible: %s.\n", optarg,
340 if (options.num_identity_files >=
341 SSH_MAX_IDENTITY_FILES)
342 fatal("Too many identity files specified "
343 "(max %d)", SSH_MAX_IDENTITY_FILES);
344 options.identity_files[options.num_identity_files++] =
349 options.smartcard_device = xstrdup(optarg);
351 fprintf(stderr, "no support for smartcards.\n");
360 if (debug_flag == 0) {
362 options.log_level = SYSLOG_LEVEL_DEBUG1;
364 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
370 fprintf(stderr, "%s, %s\n",
371 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
376 if (options.tun_open == -1)
377 options.tun_open = SSH_TUNMODE_DEFAULT;
378 options.tun_local = a2tun(optarg, &options.tun_remote);
379 if (options.tun_local == SSH_TUNID_ERR) {
381 "Bad tun device '%s'\n", optarg);
386 options.log_level = SYSLOG_LEVEL_QUIET;
389 if (optarg[0] == '^' && optarg[2] == 0 &&
390 (u_char) optarg[1] >= 64 &&
391 (u_char) optarg[1] < 128)
392 options.escape_char = (u_char) optarg[1] & 31;
393 else if (strlen(optarg) == 1)
394 options.escape_char = (u_char) optarg[0];
395 else if (strcmp(optarg, "none") == 0)
396 options.escape_char = SSH_ESCAPECHAR_NONE;
398 fprintf(stderr, "Bad escape character '%s'.\n",
404 if (ciphers_valid(optarg)) {
406 options.ciphers = xstrdup(optarg);
407 options.cipher = SSH_CIPHER_INVALID;
410 options.cipher = cipher_number(optarg);
411 if (options.cipher == -1) {
413 "Unknown cipher type '%s'\n",
417 if (options.cipher == SSH_CIPHER_3DES)
418 options.ciphers = "3des-cbc";
419 else if (options.cipher == SSH_CIPHER_BLOWFISH)
420 options.ciphers = "blowfish-cbc";
422 options.ciphers = (char *)-1;
426 if (mac_valid(optarg))
427 options.macs = xstrdup(optarg);
429 fprintf(stderr, "Unknown mac type '%s'\n",
435 if (options.control_master == SSHCTL_MASTER_YES)
436 options.control_master = SSHCTL_MASTER_ASK;
438 options.control_master = SSHCTL_MASTER_YES;
441 options.port = a2port(optarg);
442 if (options.port == 0) {
443 fprintf(stderr, "Bad port '%s'\n", optarg);
448 options.user = optarg;
452 if (parse_forward(&fwd, optarg))
453 add_local_forward(&options, &fwd);
456 "Bad local forwarding specification '%s'\n",
463 if (parse_forward(&fwd, optarg)) {
464 add_remote_forward(&options, &fwd);
467 "Bad remote forwarding specification "
474 cp = p = xstrdup(optarg);
475 memset(&fwd, '\0', sizeof(fwd));
476 fwd.connect_host = "socks";
477 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
478 fprintf(stderr, "Bad dynamic forwarding "
479 "specification '%.100s'\n", optarg);
483 fwd.listen_port = a2port(cp);
485 cleanhostname(fwd.listen_host);
487 fwd.listen_port = a2port(fwd.listen_host);
488 fwd.listen_host = NULL;
491 if (fwd.listen_port == 0) {
492 fprintf(stderr, "Bad dynamic port '%s'\n",
496 add_local_forward(&options, &fwd);
501 options.compression = 1;
512 line = xstrdup(optarg);
513 if (process_config_line(&options, host ? host : "",
514 line, "command-line", 0, &dummy) != 0)
522 if (options.control_path != NULL)
523 free(options.control_path);
524 options.control_path = xstrdup(optarg);
527 options.bind_address = optarg;
540 if (ac > 0 && !host && **av != '-') {
541 if (strrchr(*av, '@')) {
543 cp = strrchr(p, '@');
544 if (cp == NULL || cp == p)
552 optind = optreset = 1;
558 /* Check that we got a host name. */
562 SSLeay_add_all_algorithms();
563 ERR_load_crypto_strings();
565 /* Initialize the command to execute on remote host. */
566 buffer_init(&command);
569 * Save the command to execute on the remote host in a buffer. There
570 * is no limit on the length of the command, except by the maximum
571 * packet size. Also sets the tty flag if there is no command.
574 /* No command specified - execute shell on a tty. */
576 if (subsystem_flag) {
578 "You must specify a subsystem to invoke.\n");
582 /* A command has been specified. Store it into the buffer. */
583 for (i = 0; i < ac; i++) {
585 buffer_append(&command, " ", 1);
586 buffer_append(&command, av[i], strlen(av[i]));
590 /* Cannot fork to background if no command. */
591 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
593 fatal("Cannot fork into background without a command "
596 /* Allocate a tty by default if no command specified. */
597 if (buffer_len(&command) == 0)
603 /* Do not allocate a tty if stdin is not a tty. */
604 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
606 logit("Pseudo-terminal will not be allocated because "
607 "stdin is not a terminal.");
612 * Initialize "log" output. Since we are the client all output
613 * actually goes to stderr.
616 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
617 SYSLOG_FACILITY_USER, 1);
620 * Read per-user configuration file. Ignore the system wide config
621 * file if the user specifies a config file on the command line.
623 if (config != NULL) {
624 if (!read_config_file(config, host, &options, 0))
625 fatal("Can't open user config file %.100s: "
626 "%.100s", config, strerror(errno));
628 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
629 _PATH_SSH_USER_CONFFILE);
630 (void)read_config_file(buf, host, &options, 1);
632 /* Read systemwide configuration file after use config. */
633 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
637 /* Fill configuration defaults. */
638 fill_default_options(&options);
640 channel_set_af(options.address_family);
643 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
647 if (options.user == NULL)
648 options.user = xstrdup(pw->pw_name);
650 if (options.hostname != NULL)
651 host = options.hostname;
653 /* force lowercase for hostkey matching */
654 if (options.host_key_alias != NULL) {
655 for (p = options.host_key_alias; *p; p++)
657 *p = (char)tolower(*p);
660 /* Get default port if port has not been set. */
661 if (options.port == 0) {
662 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
663 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
666 if (options.proxy_command != NULL &&
667 strcmp(options.proxy_command, "none") == 0) {
668 xfree(options.proxy_command);
669 options.proxy_command = NULL;
671 if (options.control_path != NULL &&
672 strcmp(options.control_path, "none") == 0) {
673 xfree(options.control_path);
674 options.control_path = NULL;
677 if (options.control_path != NULL) {
678 char thishost[NI_MAXHOST];
680 if (gethostname(thishost, sizeof(thishost)) == -1)
681 fatal("gethostname: %s", strerror(errno));
682 snprintf(buf, sizeof(buf), "%d", options.port);
683 cp = tilde_expand_filename(options.control_path,
685 xfree(options.control_path);
686 options.control_path = percent_expand(cp, "p", buf, "h", host,
687 "r", options.user, "l", thishost, (char *)NULL);
690 if (muxclient_command != 0 && options.control_path == NULL)
691 fatal("No ControlPath specified for \"-O\" command");
692 if (options.control_path != NULL)
693 muxclient(options.control_path);
695 timeout_ms = options.connection_timeout * 1000;
697 /* Open a connection to the remote host. */
698 if (ssh_connect(host, &hostaddr, options.port,
699 options.address_family, options.connection_attempts, &timeout_ms,
700 options.tcp_keep_alive,
702 options.use_privileged_port,
704 original_effective_uid == 0 && options.use_privileged_port,
706 options.proxy_command) != 0)
710 debug3("timeout: %d ms remain after connect", timeout_ms);
713 * If we successfully made the connection, load the host private key
714 * in case we will need it later for combined rsa-rhosts
715 * authentication. This must be done before releasing extra
716 * privileges, because the file is only readable by root.
717 * If we cannot access the private keys, load the public keys
718 * instead and try to execute the ssh-keysign helper instead.
720 sensitive_data.nkeys = 0;
721 sensitive_data.keys = NULL;
722 sensitive_data.external_keysign = 0;
723 if (options.rhosts_rsa_authentication ||
724 options.hostbased_authentication) {
725 sensitive_data.nkeys = 3;
726 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
730 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
731 _PATH_HOST_KEY_FILE, "", NULL, NULL);
732 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
733 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
734 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
735 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
738 if (options.hostbased_authentication == 1 &&
739 sensitive_data.keys[0] == NULL &&
740 sensitive_data.keys[1] == NULL &&
741 sensitive_data.keys[2] == NULL) {
742 sensitive_data.keys[1] = key_load_public(
743 _PATH_HOST_DSA_KEY_FILE, NULL);
744 sensitive_data.keys[2] = key_load_public(
745 _PATH_HOST_RSA_KEY_FILE, NULL);
746 sensitive_data.external_keysign = 1;
750 * Get rid of any extra privileges that we may have. We will no
751 * longer need them. Also, extra privileges could make it very hard
752 * to read identity files and other non-world-readable files from the
753 * user's home directory if it happens to be on a NFS volume where
754 * root is mapped to nobody.
756 if (original_effective_uid == 0) {
758 permanently_set_uid(pw);
762 * Now that we are back to our own permissions, create ~/.ssh
763 * directory if it doesn't already exist.
765 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir,
766 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
767 if (stat(buf, &st) < 0)
768 if (mkdir(buf, 0700) < 0)
769 error("Could not create directory '%.200s'.", buf);
771 /* load options.identity_files */
772 load_public_identity_files();
774 /* Expand ~ in known host file names. */
776 options.system_hostfile =
777 tilde_expand_filename(options.system_hostfile, original_real_uid);
778 options.user_hostfile =
779 tilde_expand_filename(options.user_hostfile, original_real_uid);
780 options.system_hostfile2 =
781 tilde_expand_filename(options.system_hostfile2, original_real_uid);
782 options.user_hostfile2 =
783 tilde_expand_filename(options.user_hostfile2, original_real_uid);
785 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
787 /* Log into the remote system. Never returns if the login fails. */
788 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
791 /* We no longer need the private host keys. Clear them now. */
792 if (sensitive_data.nkeys != 0) {
793 for (i = 0; i < sensitive_data.nkeys; i++) {
794 if (sensitive_data.keys[i] != NULL) {
795 /* Destroys contents safely */
796 debug3("clear hostkey %d", i);
797 key_free(sensitive_data.keys[i]);
798 sensitive_data.keys[i] = NULL;
801 xfree(sensitive_data.keys);
803 for (i = 0; i < options.num_identity_files; i++) {
804 if (options.identity_files[i]) {
805 xfree(options.identity_files[i]);
806 options.identity_files[i] = NULL;
808 if (options.identity_keys[i]) {
809 key_free(options.identity_keys[i]);
810 options.identity_keys[i] = NULL;
814 exit_status = compat20 ? ssh_session2() : ssh_session();
817 if (options.control_path != NULL && muxserver_sock != -1)
818 unlink(options.control_path);
821 * Send SIGHUP to proxy command if used. We don't wait() in
822 * case it hangs and instead rely on init to reap the child
824 if (proxy_command_pid > 1)
825 kill(proxy_command_pid, SIGHUP);
830 /* Callback for remote forward global requests */
832 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
834 Forward *rfwd = (Forward *)ctxt;
836 debug("remote forward %s for: listen %d, connect %s:%d",
837 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
838 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
839 if (type == SSH2_MSG_REQUEST_FAILURE) {
840 if (options.exit_on_forward_failure)
841 fatal("Error: remote port forwarding failed for "
842 "listen port %d", rfwd->listen_port);
844 logit("Warning: remote port forwarding failed for "
845 "listen port %d", rfwd->listen_port);
847 if (++remote_forward_confirms_received == options.num_remote_forwards)
848 debug("All remote forwarding requests processed");
849 /* XXX fork-after-authentication */
853 ssh_init_forwarding(void)
858 /* Initiate local TCP/IP port forwardings. */
859 for (i = 0; i < options.num_local_forwards; i++) {
860 debug("Local connections to %.200s:%d forwarded to remote "
862 (options.local_forwards[i].listen_host == NULL) ?
863 (options.gateway_ports ? "*" : "LOCALHOST") :
864 options.local_forwards[i].listen_host,
865 options.local_forwards[i].listen_port,
866 options.local_forwards[i].connect_host,
867 options.local_forwards[i].connect_port);
868 success += channel_setup_local_fwd_listener(
869 options.local_forwards[i].listen_host,
870 options.local_forwards[i].listen_port,
871 options.local_forwards[i].connect_host,
872 options.local_forwards[i].connect_port,
873 options.gateway_ports);
875 if (i > 0 && success != i && options.exit_on_forward_failure)
876 fatal("Could not request local forwarding.");
877 if (i > 0 && success == 0)
878 error("Could not request local forwarding.");
880 /* Initiate remote TCP/IP port forwardings. */
881 for (i = 0; i < options.num_remote_forwards; i++) {
882 debug("Remote connections from %.200s:%d forwarded to "
883 "local address %.200s:%d",
884 (options.remote_forwards[i].listen_host == NULL) ?
885 "LOCALHOST" : options.remote_forwards[i].listen_host,
886 options.remote_forwards[i].listen_port,
887 options.remote_forwards[i].connect_host,
888 options.remote_forwards[i].connect_port);
889 if (channel_request_remote_forwarding(
890 options.remote_forwards[i].listen_host,
891 options.remote_forwards[i].listen_port,
892 options.remote_forwards[i].connect_host,
893 options.remote_forwards[i].connect_port) < 0) {
894 if (options.exit_on_forward_failure)
895 fatal("Could not request remote forwarding.");
897 logit("Warning: Could not request remote "
900 client_register_global_confirm(ssh_confirm_remote_forward,
901 &options.remote_forwards[i]);
904 /* Initiate tunnel forwarding. */
905 if (options.tun_open != SSH_TUNMODE_NO) {
906 if (client_request_tun_fwd(options.tun_open,
907 options.tun_local, options.tun_remote) == -1) {
908 if (options.exit_on_forward_failure)
909 fatal("Could not request tunnel forwarding.");
911 error("Could not request tunnel forwarding.");
917 check_agent_present(void)
919 if (options.forward_agent) {
920 /* Clear agent forwarding if we don't have an agent. */
921 if (!ssh_agent_present())
922 options.forward_agent = 0;
936 /* Enable compression if requested. */
937 if (options.compression) {
938 debug("Requesting compression at level %d.",
939 options.compression_level);
941 if (options.compression_level < 1 ||
942 options.compression_level > 9)
943 fatal("Compression level must be from 1 (fast) to "
946 /* Send the request. */
947 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
948 packet_put_int(options.compression_level);
951 type = packet_read();
952 if (type == SSH_SMSG_SUCCESS)
953 packet_start_compression(options.compression_level);
954 else if (type == SSH_SMSG_FAILURE)
955 logit("Warning: Remote host refused compression.");
957 packet_disconnect("Protocol error waiting for "
958 "compression response.");
960 /* Allocate a pseudo tty if appropriate. */
962 debug("Requesting pty.");
964 /* Start the packet. */
965 packet_start(SSH_CMSG_REQUEST_PTY);
967 /* Store TERM in the packet. There is no limit on the
968 length of the string. */
972 packet_put_cstring(cp);
974 /* Store window size in the packet. */
975 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
976 memset(&ws, 0, sizeof(ws));
977 packet_put_int((u_int)ws.ws_row);
978 packet_put_int((u_int)ws.ws_col);
979 packet_put_int((u_int)ws.ws_xpixel);
980 packet_put_int((u_int)ws.ws_ypixel);
982 /* Store tty modes in the packet. */
983 tty_make_modes(fileno(stdin), NULL);
985 /* Send the packet, and wait for it to leave. */
989 /* Read response from the server. */
990 type = packet_read();
991 if (type == SSH_SMSG_SUCCESS) {
994 } else if (type == SSH_SMSG_FAILURE)
995 logit("Warning: Remote host failed or refused to "
996 "allocate a pseudo tty.");
998 packet_disconnect("Protocol error waiting for pty "
999 "request response.");
1001 /* Request X11 forwarding if enabled and DISPLAY is set. */
1002 display = getenv("DISPLAY");
1003 if (options.forward_x11 && display != NULL) {
1005 /* Get reasonable local authentication information. */
1006 client_x11_get_proto(display, options.xauth_location,
1007 options.forward_x11_trusted, &proto, &data);
1008 /* Request forwarding with authentication spoofing. */
1009 debug("Requesting X11 forwarding with authentication "
1011 x11_request_forwarding_with_spoofing(0, display, proto, data);
1013 /* Read response from the server. */
1014 type = packet_read();
1015 if (type == SSH_SMSG_SUCCESS) {
1017 } else if (type == SSH_SMSG_FAILURE) {
1018 logit("Warning: Remote host denied X11 forwarding.");
1020 packet_disconnect("Protocol error waiting for X11 "
1024 /* Tell the packet module whether this is an interactive session. */
1025 packet_set_interactive(interactive);
1027 /* Request authentication agent forwarding if appropriate. */
1028 check_agent_present();
1030 if (options.forward_agent) {
1031 debug("Requesting authentication agent forwarding.");
1032 auth_request_forwarding();
1034 /* Read response from the server. */
1035 type = packet_read();
1037 if (type != SSH_SMSG_SUCCESS)
1038 logit("Warning: Remote host denied authentication agent forwarding.");
1041 /* Initiate port forwardings. */
1042 ssh_init_forwarding();
1044 /* Execute a local command */
1045 if (options.local_command != NULL &&
1046 options.permit_local_command)
1047 ssh_local_cmd(options.local_command);
1049 /* If requested, let ssh continue in the background. */
1050 if (fork_after_authentication_flag)
1051 if (daemon(1, 1) < 0)
1052 fatal("daemon() failed: %.200s", strerror(errno));
1055 * If a command was specified on the command line, execute the
1056 * command now. Otherwise request the server to start a shell.
1058 if (buffer_len(&command) > 0) {
1059 int len = buffer_len(&command);
1062 debug("Sending command: %.*s", len,
1063 (u_char *)buffer_ptr(&command));
1064 packet_start(SSH_CMSG_EXEC_CMD);
1065 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1067 packet_write_wait();
1069 debug("Requesting shell.");
1070 packet_start(SSH_CMSG_EXEC_SHELL);
1072 packet_write_wait();
1075 /* Enter the interactive session. */
1076 return client_loop(have_tty, tty_flag ?
1077 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1080 /* request pty/x11/agent/tcpfwd/shell for channel */
1082 ssh_session2_setup(int id, void *arg)
1084 extern char **environ;
1085 const char *display;
1086 int interactive = tty_flag;
1088 display = getenv("DISPLAY");
1089 if (options.forward_x11 && display != NULL) {
1091 /* Get reasonable local authentication information. */
1092 client_x11_get_proto(display, options.xauth_location,
1093 options.forward_x11_trusted, &proto, &data);
1094 /* Request forwarding with authentication spoofing. */
1095 debug("Requesting X11 forwarding with authentication "
1097 x11_request_forwarding_with_spoofing(id, display, proto, data);
1099 /* XXX wait for reply */
1102 check_agent_present();
1103 if (options.forward_agent) {
1104 debug("Requesting authentication agent forwarding.");
1105 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1109 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1110 NULL, fileno(stdin), &command, environ);
1112 packet_set_interactive(interactive);
1115 /* open new channel for a session */
1117 ssh_session2_open(void)
1120 int window, packetmax, in, out, err;
1122 if (stdin_null_flag) {
1123 in = open(_PATH_DEVNULL, O_RDONLY);
1125 in = dup(STDIN_FILENO);
1127 out = dup(STDOUT_FILENO);
1128 err = dup(STDERR_FILENO);
1130 if (in < 0 || out < 0 || err < 0)
1131 fatal("dup() in/out/err failed");
1133 /* enable nonblocking unless tty */
1141 window = CHAN_SES_WINDOW_DEFAULT;
1142 packetmax = CHAN_SES_PACKET_DEFAULT;
1148 "session", SSH_CHANNEL_OPENING, in, out, err,
1149 window, packetmax, CHAN_EXTENDED_WRITE,
1150 "client-session", /*nonblock*/0);
1152 debug3("ssh_session2_open: channel_new: %d", c->self);
1154 channel_send_open(c->self);
1156 channel_register_open_confirm(c->self,
1157 ssh_session2_setup, NULL);
1167 /* XXX should be pre-session */
1168 ssh_init_forwarding();
1170 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1171 id = ssh_session2_open();
1173 /* If we don't expect to open a new session, then disallow it */
1174 if (options.control_master == SSHCTL_MASTER_NO) {
1175 debug("Requesting no-more-sessions@openssh.com");
1176 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1177 packet_put_cstring("no-more-sessions@openssh.com");
1182 /* Execute a local command */
1183 if (options.local_command != NULL &&
1184 options.permit_local_command)
1185 ssh_local_cmd(options.local_command);
1187 /* Start listening for multiplex clients */
1190 /* If requested, let ssh continue in the background. */
1191 if (fork_after_authentication_flag)
1192 if (daemon(1, 1) < 0)
1193 fatal("daemon() failed: %.200s", strerror(errno));
1195 return client_loop(tty_flag, tty_flag ?
1196 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1200 load_public_identity_files(void)
1202 char *filename, *cp, thishost[NI_MAXHOST];
1203 char *pwdir = NULL, *pwname = NULL;
1210 if (options.smartcard_device != NULL &&
1211 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1212 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1214 for (i = 0; keys[i] != NULL; i++) {
1216 memmove(&options.identity_files[1],
1217 &options.identity_files[0],
1218 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1219 memmove(&options.identity_keys[1],
1220 &options.identity_keys[0],
1221 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1222 options.num_identity_files++;
1223 options.identity_keys[0] = keys[i];
1224 options.identity_files[0] = sc_get_key_label(keys[i]);
1226 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1227 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1231 #endif /* SMARTCARD */
1232 if ((pw = getpwuid(original_real_uid)) == NULL)
1233 fatal("load_public_identity_files: getpwuid failed");
1234 pwname = xstrdup(pw->pw_name);
1235 pwdir = xstrdup(pw->pw_dir);
1236 if (gethostname(thishost, sizeof(thishost)) == -1)
1237 fatal("load_public_identity_files: gethostname: %s",
1239 for (; i < options.num_identity_files; i++) {
1240 cp = tilde_expand_filename(options.identity_files[i],
1242 filename = percent_expand(cp, "d", pwdir,
1243 "u", pwname, "l", thishost, "h", host,
1244 "r", options.user, (char *)NULL);
1246 public = key_load_public(filename, NULL);
1247 debug("identity file %s type %d", filename,
1248 public ? public->type : -1);
1249 xfree(options.identity_files[i]);
1250 options.identity_files[i] = filename;
1251 options.identity_keys[i] = public;
1253 bzero(pwname, strlen(pwname));
1255 bzero(pwdir, strlen(pwdir));