]> andersk Git - openssh.git/blob - ssh.c
- stevesk@cvs.openbsd.org 2006/07/06 16:03:53
[openssh.git] / ssh.c
1 /* $OpenBSD: ssh.c,v 1.279 2006/07/06 16:03:53 stevesk Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
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.
9  *
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".
15  *
16  * Copyright (c) 1999 Niels Provos.  All rights reserved.
17  * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl.  All rights reserved.
18  *
19  * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20  * in Canada (German citizen).
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
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.
30  *
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.
41  */
42
43 #include "includes.h"
44
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
48 #endif
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/un.h>
52
53 #include <ctype.h>
54 #ifdef HAVE_PATHS_H
55 #include <paths.h>
56 #endif
57 #include <pwd.h>
58 #include <signal.h>
59
60 #include <openssl/evp.h>
61 #include <openssl/err.h>
62
63 #include "ssh.h"
64 #include "ssh1.h"
65 #include "ssh2.h"
66 #include "compat.h"
67 #include "cipher.h"
68 #include "xmalloc.h"
69 #include "packet.h"
70 #include "buffer.h"
71 #include "bufaux.h"
72 #include "channels.h"
73 #include "key.h"
74 #include "authfd.h"
75 #include "authfile.h"
76 #include "pathnames.h"
77 #include "dispatch.h"
78 #include "clientloop.h"
79 #include "log.h"
80 #include "readconf.h"
81 #include "sshconnect.h"
82 #include "misc.h"
83 #include "kex.h"
84 #include "mac.h"
85 #include "sshpty.h"
86 #include "match.h"
87 #include "msg.h"
88 #include "monitor_fdpass.h"
89 #include "uidswap.h"
90 #include "version.h"
91
92 #ifdef SMARTCARD
93 #include "scard.h"
94 #endif
95
96 extern char *__progname;
97
98 /* Flag indicating whether debug mode is on.  This can be set on the command line. */
99 int debug_flag = 0;
100
101 /* Flag indicating whether a tty should be allocated */
102 int tty_flag = 0;
103 int no_tty_flag = 0;
104 int force_tty_flag = 0;
105
106 /* don't exec a shell */
107 int no_shell_flag = 0;
108
109 /*
110  * Flag indicating that nothing should be read from stdin.  This can be set
111  * on the command line.
112  */
113 int stdin_null_flag = 0;
114
115 /*
116  * Flag indicating that ssh should fork after authentication.  This is useful
117  * so that the passphrase can be entered manually, and then ssh goes to the
118  * background.
119  */
120 int fork_after_authentication_flag = 0;
121
122 /*
123  * General data structure for command line options and options configurable
124  * in configuration files.  See readconf.h.
125  */
126 Options options;
127
128 /* optional user configfile */
129 char *config = NULL;
130
131 /*
132  * Name of the host we are connecting to.  This is the name given on the
133  * command line, or the HostName specified for the user-supplied name in a
134  * configuration file.
135  */
136 char *host;
137
138 /* socket address the host resolves to */
139 struct sockaddr_storage hostaddr;
140
141 /* Private host keys. */
142 Sensitive sensitive_data;
143
144 /* Original real UID. */
145 uid_t original_real_uid;
146 uid_t original_effective_uid;
147
148 /* command to be executed */
149 Buffer command;
150
151 /* Should we execute a command or invoke a subsystem? */
152 int subsystem_flag = 0;
153
154 /* # of replies received for global requests */
155 static int client_global_request_id = 0;
156
157 /* pid of proxycommand child process */
158 pid_t proxy_command_pid = 0;
159
160 /* fd to control socket */
161 int control_fd = -1;
162
163 /* Multiplexing control command */
164 static u_int mux_command = 0;
165
166 /* Only used in control client mode */
167 volatile sig_atomic_t control_client_terminate = 0;
168 u_int control_server_pid = 0;
169
170 /* Prints a help message to the user.  This function never returns. */
171
172 static void
173 usage(void)
174 {
175         fprintf(stderr,
176 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
177 "           [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
178 "           [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
179 "           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
180 "           [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
181 "           [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
182         );
183         exit(255);
184 }
185
186 static int ssh_session(void);
187 static int ssh_session2(void);
188 static void load_public_identity_files(void);
189 static void control_client(const char *path);
190
191 /*
192  * Main program for the ssh client.
193  */
194 int
195 main(int ac, char **av)
196 {
197         int i, opt, exit_status;
198         char *p, *cp, *line, buf[256];
199         struct stat st;
200         struct passwd *pw;
201         int dummy;
202         extern int optind, optreset;
203         extern char *optarg;
204         struct servent *sp;
205         Forward fwd;
206
207         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
208         sanitise_stdfd();
209
210         __progname = ssh_get_progname(av[0]);
211         init_rng();
212
213         /*
214          * Save the original real uid.  It will be needed later (uid-swapping
215          * may clobber the real uid).
216          */
217         original_real_uid = getuid();
218         original_effective_uid = geteuid();
219
220         /*
221          * Use uid-swapping to give up root privileges for the duration of
222          * option processing.  We will re-instantiate the rights when we are
223          * ready to create the privileged port, and will permanently drop
224          * them when the port has been created (actually, when the connection
225          * has been made, as we may need to create the port several times).
226          */
227         PRIV_END;
228
229 #ifdef HAVE_SETRLIMIT
230         /* If we are installed setuid root be careful to not drop core. */
231         if (original_real_uid != original_effective_uid) {
232                 struct rlimit rlim;
233                 rlim.rlim_cur = rlim.rlim_max = 0;
234                 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
235                         fatal("setrlimit failed: %.100s", strerror(errno));
236         }
237 #endif
238         /* Get user data. */
239         pw = getpwuid(original_real_uid);
240         if (!pw) {
241                 logit("You don't exist, go away!");
242                 exit(255);
243         }
244         /* Take a copy of the returned structure. */
245         pw = pwcopy(pw);
246
247         /*
248          * Set our umask to something reasonable, as some files are created
249          * with the default umask.  This will make them world-readable but
250          * writable only by the owner, which is ok for all files for which we
251          * don't set the modes explicitly.
252          */
253         umask(022);
254
255         /* Initialize option structure to indicate that no values have been set. */
256         initialize_options(&options);
257
258         /* Parse command-line arguments. */
259         host = NULL;
260
261  again:
262         while ((opt = getopt(ac, av,
263             "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
264                 switch (opt) {
265                 case '1':
266                         options.protocol = SSH_PROTO_1;
267                         break;
268                 case '2':
269                         options.protocol = SSH_PROTO_2;
270                         break;
271                 case '4':
272                         options.address_family = AF_INET;
273                         break;
274                 case '6':
275                         options.address_family = AF_INET6;
276                         break;
277                 case 'n':
278                         stdin_null_flag = 1;
279                         break;
280                 case 'f':
281                         fork_after_authentication_flag = 1;
282                         stdin_null_flag = 1;
283                         break;
284                 case 'x':
285                         options.forward_x11 = 0;
286                         break;
287                 case 'X':
288                         options.forward_x11 = 1;
289                         break;
290                 case 'Y':
291                         options.forward_x11 = 1;
292                         options.forward_x11_trusted = 1;
293                         break;
294                 case 'g':
295                         options.gateway_ports = 1;
296                         break;
297                 case 'O':
298                         if (strcmp(optarg, "check") == 0)
299                                 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
300                         else if (strcmp(optarg, "exit") == 0)
301                                 mux_command = SSHMUX_COMMAND_TERMINATE;
302                         else
303                                 fatal("Invalid multiplex command.");
304                         break;
305                 case 'P':       /* deprecated */
306                         options.use_privileged_port = 0;
307                         break;
308                 case 'a':
309                         options.forward_agent = 0;
310                         break;
311                 case 'A':
312                         options.forward_agent = 1;
313                         break;
314                 case 'k':
315                         options.gss_deleg_creds = 0;
316                         break;
317                 case 'i':
318                         if (stat(optarg, &st) < 0) {
319                                 fprintf(stderr, "Warning: Identity file %s "
320                                     "not accessible: %s.\n", optarg,
321                                     strerror(errno));
322                                 break;
323                         }
324                         if (options.num_identity_files >=
325                             SSH_MAX_IDENTITY_FILES)
326                                 fatal("Too many identity files specified "
327                                     "(max %d)", SSH_MAX_IDENTITY_FILES);
328                         options.identity_files[options.num_identity_files++] =
329                             xstrdup(optarg);
330                         break;
331                 case 'I':
332 #ifdef SMARTCARD
333                         options.smartcard_device = xstrdup(optarg);
334 #else
335                         fprintf(stderr, "no support for smartcards.\n");
336 #endif
337                         break;
338                 case 't':
339                         if (tty_flag)
340                                 force_tty_flag = 1;
341                         tty_flag = 1;
342                         break;
343                 case 'v':
344                         if (debug_flag == 0) {
345                                 debug_flag = 1;
346                                 options.log_level = SYSLOG_LEVEL_DEBUG1;
347                         } else {
348                                 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
349                                         options.log_level++;
350                                 break;
351                         }
352                         /* FALLTHROUGH */
353                 case 'V':
354                         fprintf(stderr, "%s, %s\n",
355                             SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
356                         if (opt == 'V')
357                                 exit(0);
358                         break;
359                 case 'w':
360                         if (options.tun_open == -1)
361                                 options.tun_open = SSH_TUNMODE_DEFAULT;
362                         options.tun_local = a2tun(optarg, &options.tun_remote);
363                         if (options.tun_local == SSH_TUNID_ERR) {
364                                 fprintf(stderr, "Bad tun device '%s'\n", optarg);
365                                 exit(255);
366                         }
367                         break;
368                 case 'q':
369                         options.log_level = SYSLOG_LEVEL_QUIET;
370                         break;
371                 case 'e':
372                         if (optarg[0] == '^' && optarg[2] == 0 &&
373                             (u_char) optarg[1] >= 64 &&
374                             (u_char) optarg[1] < 128)
375                                 options.escape_char = (u_char) optarg[1] & 31;
376                         else if (strlen(optarg) == 1)
377                                 options.escape_char = (u_char) optarg[0];
378                         else if (strcmp(optarg, "none") == 0)
379                                 options.escape_char = SSH_ESCAPECHAR_NONE;
380                         else {
381                                 fprintf(stderr, "Bad escape character '%s'.\n",
382                                     optarg);
383                                 exit(255);
384                         }
385                         break;
386                 case 'c':
387                         if (ciphers_valid(optarg)) {
388                                 /* SSH2 only */
389                                 options.ciphers = xstrdup(optarg);
390                                 options.cipher = SSH_CIPHER_INVALID;
391                         } else {
392                                 /* SSH1 only */
393                                 options.cipher = cipher_number(optarg);
394                                 if (options.cipher == -1) {
395                                         fprintf(stderr,
396                                             "Unknown cipher type '%s'\n",
397                                             optarg);
398                                         exit(255);
399                                 }
400                                 if (options.cipher == SSH_CIPHER_3DES)
401                                         options.ciphers = "3des-cbc";
402                                 else if (options.cipher == SSH_CIPHER_BLOWFISH)
403                                         options.ciphers = "blowfish-cbc";
404                                 else
405                                         options.ciphers = (char *)-1;
406                         }
407                         break;
408                 case 'm':
409                         if (mac_valid(optarg))
410                                 options.macs = xstrdup(optarg);
411                         else {
412                                 fprintf(stderr, "Unknown mac type '%s'\n",
413                                     optarg);
414                                 exit(255);
415                         }
416                         break;
417                 case 'M':
418                         if (options.control_master == SSHCTL_MASTER_YES)
419                                 options.control_master = SSHCTL_MASTER_ASK;
420                         else
421                                 options.control_master = SSHCTL_MASTER_YES;
422                         break;
423                 case 'p':
424                         options.port = a2port(optarg);
425                         if (options.port == 0) {
426                                 fprintf(stderr, "Bad port '%s'\n", optarg);
427                                 exit(255);
428                         }
429                         break;
430                 case 'l':
431                         options.user = optarg;
432                         break;
433
434                 case 'L':
435                         if (parse_forward(&fwd, optarg))
436                                 add_local_forward(&options, &fwd);
437                         else {
438                                 fprintf(stderr,
439                                     "Bad local forwarding specification '%s'\n",
440                                     optarg);
441                                 exit(255);
442                         }
443                         break;
444
445                 case 'R':
446                         if (parse_forward(&fwd, optarg)) {
447                                 add_remote_forward(&options, &fwd);
448                         } else {
449                                 fprintf(stderr,
450                                     "Bad remote forwarding specification "
451                                     "'%s'\n", optarg);
452                                 exit(255);
453                         }
454                         break;
455
456                 case 'D':
457                         cp = p = xstrdup(optarg);
458                         memset(&fwd, '\0', sizeof(fwd));
459                         fwd.connect_host = "socks";
460                         if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
461                                 fprintf(stderr, "Bad dynamic forwarding "
462                                     "specification '%.100s'\n", optarg);
463                                 exit(255);
464                         }
465                         if (cp != NULL) {
466                                 fwd.listen_port = a2port(cp);
467                                 fwd.listen_host = cleanhostname(fwd.listen_host);
468                         } else {
469                                 fwd.listen_port = a2port(fwd.listen_host);
470                                 fwd.listen_host = NULL;
471                         }
472
473                         if (fwd.listen_port == 0) {
474                                 fprintf(stderr, "Bad dynamic port '%s'\n",
475                                     optarg);
476                                 exit(255);
477                         }
478                         add_local_forward(&options, &fwd);
479                         xfree(p);
480                         break;
481
482                 case 'C':
483                         options.compression = 1;
484                         break;
485                 case 'N':
486                         no_shell_flag = 1;
487                         no_tty_flag = 1;
488                         break;
489                 case 'T':
490                         no_tty_flag = 1;
491                         break;
492                 case 'o':
493                         dummy = 1;
494                         line = xstrdup(optarg);
495                         if (process_config_line(&options, host ? host : "",
496                             line, "command-line", 0, &dummy) != 0)
497                                 exit(255);
498                         xfree(line);
499                         break;
500                 case 's':
501                         subsystem_flag = 1;
502                         break;
503                 case 'S':
504                         if (options.control_path != NULL)
505                                 free(options.control_path);
506                         options.control_path = xstrdup(optarg);
507                         break;
508                 case 'b':
509                         options.bind_address = optarg;
510                         break;
511                 case 'F':
512                         config = optarg;
513                         break;
514                 default:
515                         usage();
516                 }
517         }
518
519         ac -= optind;
520         av += optind;
521
522         if (ac > 0 && !host && **av != '-') {
523                 if (strrchr(*av, '@')) {
524                         p = xstrdup(*av);
525                         cp = strrchr(p, '@');
526                         if (cp == NULL || cp == p)
527                                 usage();
528                         options.user = p;
529                         *cp = '\0';
530                         host = ++cp;
531                 } else
532                         host = *av;
533                 if (ac > 1) {
534                         optind = optreset = 1;
535                         goto again;
536                 }
537                 ac--, av++;
538         }
539
540         /* Check that we got a host name. */
541         if (!host)
542                 usage();
543
544         SSLeay_add_all_algorithms();
545         ERR_load_crypto_strings();
546
547         /* Initialize the command to execute on remote host. */
548         buffer_init(&command);
549
550         /*
551          * Save the command to execute on the remote host in a buffer. There
552          * is no limit on the length of the command, except by the maximum
553          * packet size.  Also sets the tty flag if there is no command.
554          */
555         if (!ac) {
556                 /* No command specified - execute shell on a tty. */
557                 tty_flag = 1;
558                 if (subsystem_flag) {
559                         fprintf(stderr,
560                             "You must specify a subsystem to invoke.\n");
561                         usage();
562                 }
563         } else {
564                 /* A command has been specified.  Store it into the buffer. */
565                 for (i = 0; i < ac; i++) {
566                         if (i)
567                                 buffer_append(&command, " ", 1);
568                         buffer_append(&command, av[i], strlen(av[i]));
569                 }
570         }
571
572         /* Cannot fork to background if no command. */
573         if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
574                 fatal("Cannot fork into background without a command to execute.");
575
576         /* Allocate a tty by default if no command specified. */
577         if (buffer_len(&command) == 0)
578                 tty_flag = 1;
579
580         /* Force no tty */
581         if (no_tty_flag)
582                 tty_flag = 0;
583         /* Do not allocate a tty if stdin is not a tty. */
584         if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
585                 if (tty_flag)
586                         logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
587                 tty_flag = 0;
588         }
589
590         /*
591          * Initialize "log" output.  Since we are the client all output
592          * actually goes to stderr.
593          */
594         log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
595             SYSLOG_FACILITY_USER, 1);
596
597         /*
598          * Read per-user configuration file.  Ignore the system wide config
599          * file if the user specifies a config file on the command line.
600          */
601         if (config != NULL) {
602                 if (!read_config_file(config, host, &options, 0))
603                         fatal("Can't open user config file %.100s: "
604                             "%.100s", config, strerror(errno));
605         } else  {
606                 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
607                     _PATH_SSH_USER_CONFFILE);
608                 (void)read_config_file(buf, host, &options, 1);
609
610                 /* Read systemwide configuration file after use config. */
611                 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
612                     &options, 0);
613         }
614
615         /* Fill configuration defaults. */
616         fill_default_options(&options);
617
618         channel_set_af(options.address_family);
619
620         /* reinit */
621         log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
622
623         seed_rng();
624
625         if (options.user == NULL)
626                 options.user = xstrdup(pw->pw_name);
627
628         if (options.hostname != NULL)
629                 host = options.hostname;
630
631         /* force lowercase for hostkey matching */
632         if (options.host_key_alias != NULL) {
633                 for (p = options.host_key_alias; *p; p++)
634                         if (isupper(*p))
635                                 *p = (char)tolower(*p);
636         }
637
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;
642         }
643
644         if (options.proxy_command != NULL &&
645             strcmp(options.proxy_command, "none") == 0)
646                 options.proxy_command = NULL;
647         if (options.control_path != NULL &&
648             strcmp(options.control_path, "none") == 0)
649                 options.control_path = NULL;
650
651         if (options.control_path != NULL) {
652                 char thishost[NI_MAXHOST];
653
654                 if (gethostname(thishost, sizeof(thishost)) == -1)
655                         fatal("gethostname: %s", strerror(errno));
656                 snprintf(buf, sizeof(buf), "%d", options.port);
657                 cp = tilde_expand_filename(options.control_path,
658                     original_real_uid);
659                 options.control_path = percent_expand(cp, "p", buf, "h", host,
660                     "r", options.user, "l", thishost, (char *)NULL);
661                 xfree(cp);
662         }
663         if (mux_command != 0 && options.control_path == NULL)
664                 fatal("No ControlPath specified for \"-O\" command");
665         if (options.control_path != NULL)
666                 control_client(options.control_path);
667
668         /* Open a connection to the remote host. */
669         if (ssh_connect(host, &hostaddr, options.port,
670             options.address_family, options.connection_attempts,
671 #ifdef HAVE_CYGWIN
672             options.use_privileged_port,
673 #else
674             original_effective_uid == 0 && options.use_privileged_port,
675 #endif
676             options.proxy_command) != 0)
677                 exit(255);
678
679         /*
680          * If we successfully made the connection, load the host private key
681          * in case we will need it later for combined rsa-rhosts
682          * authentication. This must be done before releasing extra
683          * privileges, because the file is only readable by root.
684          * If we cannot access the private keys, load the public keys
685          * instead and try to execute the ssh-keysign helper instead.
686          */
687         sensitive_data.nkeys = 0;
688         sensitive_data.keys = NULL;
689         sensitive_data.external_keysign = 0;
690         if (options.rhosts_rsa_authentication ||
691             options.hostbased_authentication) {
692                 sensitive_data.nkeys = 3;
693                 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
694                     sizeof(Key));
695
696                 PRIV_START;
697                 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
698                     _PATH_HOST_KEY_FILE, "", NULL, NULL);
699                 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
700                     _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
701                 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
702                     _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
703                 PRIV_END;
704
705                 if (options.hostbased_authentication == 1 &&
706                     sensitive_data.keys[0] == NULL &&
707                     sensitive_data.keys[1] == NULL &&
708                     sensitive_data.keys[2] == NULL) {
709                         sensitive_data.keys[1] = key_load_public(
710                             _PATH_HOST_DSA_KEY_FILE, NULL);
711                         sensitive_data.keys[2] = key_load_public(
712                             _PATH_HOST_RSA_KEY_FILE, NULL);
713                         sensitive_data.external_keysign = 1;
714                 }
715         }
716         /*
717          * Get rid of any extra privileges that we may have.  We will no
718          * longer need them.  Also, extra privileges could make it very hard
719          * to read identity files and other non-world-readable files from the
720          * user's home directory if it happens to be on a NFS volume where
721          * root is mapped to nobody.
722          */
723         if (original_effective_uid == 0) {
724                 PRIV_START;
725                 permanently_set_uid(pw);
726         }
727
728         /*
729          * Now that we are back to our own permissions, create ~/.ssh
730          * directory if it doesn't already exist.
731          */
732         snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
733         if (stat(buf, &st) < 0)
734                 if (mkdir(buf, 0700) < 0)
735                         error("Could not create directory '%.200s'.", buf);
736
737         /* load options.identity_files */
738         load_public_identity_files();
739
740         /* Expand ~ in known host file names. */
741         /* XXX mem-leaks: */
742         options.system_hostfile =
743             tilde_expand_filename(options.system_hostfile, original_real_uid);
744         options.user_hostfile =
745             tilde_expand_filename(options.user_hostfile, original_real_uid);
746         options.system_hostfile2 =
747             tilde_expand_filename(options.system_hostfile2, original_real_uid);
748         options.user_hostfile2 =
749             tilde_expand_filename(options.user_hostfile2, original_real_uid);
750
751         signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
752
753         /* Log into the remote system.  This never returns if the login fails. */
754         ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
755
756         /* We no longer need the private host keys.  Clear them now. */
757         if (sensitive_data.nkeys != 0) {
758                 for (i = 0; i < sensitive_data.nkeys; i++) {
759                         if (sensitive_data.keys[i] != NULL) {
760                                 /* Destroys contents safely */
761                                 debug3("clear hostkey %d", i);
762                                 key_free(sensitive_data.keys[i]);
763                                 sensitive_data.keys[i] = NULL;
764                         }
765                 }
766                 xfree(sensitive_data.keys);
767         }
768         for (i = 0; i < options.num_identity_files; i++) {
769                 if (options.identity_files[i]) {
770                         xfree(options.identity_files[i]);
771                         options.identity_files[i] = NULL;
772                 }
773                 if (options.identity_keys[i]) {
774                         key_free(options.identity_keys[i]);
775                         options.identity_keys[i] = NULL;
776                 }
777         }
778
779         exit_status = compat20 ? ssh_session2() : ssh_session();
780         packet_close();
781
782         if (options.control_path != NULL && control_fd != -1)
783                 unlink(options.control_path);
784
785         /*
786          * Send SIGHUP to proxy command if used. We don't wait() in
787          * case it hangs and instead rely on init to reap the child
788          */
789         if (proxy_command_pid > 1)
790                 kill(proxy_command_pid, SIGHUP);
791
792         return exit_status;
793 }
794
795 static void
796 ssh_init_forwarding(void)
797 {
798         int success = 0;
799         int i;
800
801         /* Initiate local TCP/IP port forwardings. */
802         for (i = 0; i < options.num_local_forwards; i++) {
803                 debug("Local connections to %.200s:%d forwarded to remote "
804                     "address %.200s:%d",
805                     (options.local_forwards[i].listen_host == NULL) ?
806                     (options.gateway_ports ? "*" : "LOCALHOST") :
807                     options.local_forwards[i].listen_host,
808                     options.local_forwards[i].listen_port,
809                     options.local_forwards[i].connect_host,
810                     options.local_forwards[i].connect_port);
811                 success += channel_setup_local_fwd_listener(
812                     options.local_forwards[i].listen_host,
813                     options.local_forwards[i].listen_port,
814                     options.local_forwards[i].connect_host,
815                     options.local_forwards[i].connect_port,
816                     options.gateway_ports);
817         }
818         if (i > 0 && success == 0)
819                 error("Could not request local forwarding.");
820
821         /* Initiate remote TCP/IP port forwardings. */
822         for (i = 0; i < options.num_remote_forwards; i++) {
823                 debug("Remote connections from %.200s:%d forwarded to "
824                     "local address %.200s:%d",
825                     (options.remote_forwards[i].listen_host == NULL) ?
826                     "LOCALHOST" : options.remote_forwards[i].listen_host,
827                     options.remote_forwards[i].listen_port,
828                     options.remote_forwards[i].connect_host,
829                     options.remote_forwards[i].connect_port);
830                 channel_request_remote_forwarding(
831                     options.remote_forwards[i].listen_host,
832                     options.remote_forwards[i].listen_port,
833                     options.remote_forwards[i].connect_host,
834                     options.remote_forwards[i].connect_port);
835         }
836 }
837
838 static void
839 check_agent_present(void)
840 {
841         if (options.forward_agent) {
842                 /* Clear agent forwarding if we don't have an agent. */
843                 if (!ssh_agent_present())
844                         options.forward_agent = 0;
845         }
846 }
847
848 static int
849 ssh_session(void)
850 {
851         int type;
852         int interactive = 0;
853         int have_tty = 0;
854         struct winsize ws;
855         char *cp;
856         const char *display;
857
858         /* Enable compression if requested. */
859         if (options.compression) {
860                 debug("Requesting compression at level %d.", options.compression_level);
861
862                 if (options.compression_level < 1 || options.compression_level > 9)
863                         fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
864
865                 /* Send the request. */
866                 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
867                 packet_put_int(options.compression_level);
868                 packet_send();
869                 packet_write_wait();
870                 type = packet_read();
871                 if (type == SSH_SMSG_SUCCESS)
872                         packet_start_compression(options.compression_level);
873                 else if (type == SSH_SMSG_FAILURE)
874                         logit("Warning: Remote host refused compression.");
875                 else
876                         packet_disconnect("Protocol error waiting for compression response.");
877         }
878         /* Allocate a pseudo tty if appropriate. */
879         if (tty_flag) {
880                 debug("Requesting pty.");
881
882                 /* Start the packet. */
883                 packet_start(SSH_CMSG_REQUEST_PTY);
884
885                 /* Store TERM in the packet.  There is no limit on the
886                    length of the string. */
887                 cp = getenv("TERM");
888                 if (!cp)
889                         cp = "";
890                 packet_put_cstring(cp);
891
892                 /* Store window size in the packet. */
893                 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
894                         memset(&ws, 0, sizeof(ws));
895                 packet_put_int((u_int)ws.ws_row);
896                 packet_put_int((u_int)ws.ws_col);
897                 packet_put_int((u_int)ws.ws_xpixel);
898                 packet_put_int((u_int)ws.ws_ypixel);
899
900                 /* Store tty modes in the packet. */
901                 tty_make_modes(fileno(stdin), NULL);
902
903                 /* Send the packet, and wait for it to leave. */
904                 packet_send();
905                 packet_write_wait();
906
907                 /* Read response from the server. */
908                 type = packet_read();
909                 if (type == SSH_SMSG_SUCCESS) {
910                         interactive = 1;
911                         have_tty = 1;
912                 } else if (type == SSH_SMSG_FAILURE)
913                         logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
914                 else
915                         packet_disconnect("Protocol error waiting for pty request response.");
916         }
917         /* Request X11 forwarding if enabled and DISPLAY is set. */
918         display = getenv("DISPLAY");
919         if (options.forward_x11 && display != NULL) {
920                 char *proto, *data;
921                 /* Get reasonable local authentication information. */
922                 client_x11_get_proto(display, options.xauth_location,
923                     options.forward_x11_trusted, &proto, &data);
924                 /* Request forwarding with authentication spoofing. */
925                 debug("Requesting X11 forwarding with authentication spoofing.");
926                 x11_request_forwarding_with_spoofing(0, display, proto, data);
927
928                 /* Read response from the server. */
929                 type = packet_read();
930                 if (type == SSH_SMSG_SUCCESS) {
931                         interactive = 1;
932                 } else if (type == SSH_SMSG_FAILURE) {
933                         logit("Warning: Remote host denied X11 forwarding.");
934                 } else {
935                         packet_disconnect("Protocol error waiting for X11 forwarding");
936                 }
937         }
938         /* Tell the packet module whether this is an interactive session. */
939         packet_set_interactive(interactive);
940
941         /* Request authentication agent forwarding if appropriate. */
942         check_agent_present();
943
944         if (options.forward_agent) {
945                 debug("Requesting authentication agent forwarding.");
946                 auth_request_forwarding();
947
948                 /* Read response from the server. */
949                 type = packet_read();
950                 packet_check_eom();
951                 if (type != SSH_SMSG_SUCCESS)
952                         logit("Warning: Remote host denied authentication agent forwarding.");
953         }
954
955         /* Initiate port forwardings. */
956         ssh_init_forwarding();
957
958         /* If requested, let ssh continue in the background. */
959         if (fork_after_authentication_flag)
960                 if (daemon(1, 1) < 0)
961                         fatal("daemon() failed: %.200s", strerror(errno));
962
963         /*
964          * If a command was specified on the command line, execute the
965          * command now. Otherwise request the server to start a shell.
966          */
967         if (buffer_len(&command) > 0) {
968                 int len = buffer_len(&command);
969                 if (len > 900)
970                         len = 900;
971                 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
972                 packet_start(SSH_CMSG_EXEC_CMD);
973                 packet_put_string(buffer_ptr(&command), buffer_len(&command));
974                 packet_send();
975                 packet_write_wait();
976         } else {
977                 debug("Requesting shell.");
978                 packet_start(SSH_CMSG_EXEC_SHELL);
979                 packet_send();
980                 packet_write_wait();
981         }
982
983         /* Enter the interactive session. */
984         return client_loop(have_tty, tty_flag ?
985             options.escape_char : SSH_ESCAPECHAR_NONE, 0);
986 }
987
988 static void
989 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
990 {
991         int id, len;
992
993         id = packet_get_int();
994         len = buffer_len(&command);
995         if (len > 900)
996                 len = 900;
997         packet_check_eom();
998         if (type == SSH2_MSG_CHANNEL_FAILURE)
999                 fatal("Request for subsystem '%.*s' failed on channel %d",
1000                     len, (u_char *)buffer_ptr(&command), id);
1001 }
1002
1003 void
1004 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1005 {
1006         int i;
1007
1008         i = client_global_request_id++;
1009         if (i >= options.num_remote_forwards)
1010                 return;
1011         debug("remote forward %s for: listen %d, connect %s:%d",
1012             type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1013             options.remote_forwards[i].listen_port,
1014             options.remote_forwards[i].connect_host,
1015             options.remote_forwards[i].connect_port);
1016         if (type == SSH2_MSG_REQUEST_FAILURE)
1017                 logit("Warning: remote port forwarding failed for listen "
1018                     "port %d", options.remote_forwards[i].listen_port);
1019 }
1020
1021 static void
1022 ssh_control_listener(void)
1023 {
1024         struct sockaddr_un addr;
1025         mode_t old_umask;
1026         int addr_len;
1027
1028         if (options.control_path == NULL ||
1029             options.control_master == SSHCTL_MASTER_NO)
1030                 return;
1031
1032         debug("setting up multiplex master socket");
1033
1034         memset(&addr, '\0', sizeof(addr));
1035         addr.sun_family = AF_UNIX;
1036         addr_len = offsetof(struct sockaddr_un, sun_path) +
1037             strlen(options.control_path) + 1;
1038
1039         if (strlcpy(addr.sun_path, options.control_path,
1040             sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1041                 fatal("ControlPath too long");
1042
1043         if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1044                 fatal("%s socket(): %s", __func__, strerror(errno));
1045
1046         old_umask = umask(0177);
1047         if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1048                 control_fd = -1;
1049                 if (errno == EINVAL || errno == EADDRINUSE)
1050                         fatal("ControlSocket %s already exists",
1051                             options.control_path);
1052                 else
1053                         fatal("%s bind(): %s", __func__, strerror(errno));
1054         }
1055         umask(old_umask);
1056
1057         if (listen(control_fd, 64) == -1)
1058                 fatal("%s listen(): %s", __func__, strerror(errno));
1059
1060         set_nonblock(control_fd);
1061 }
1062
1063 /* request pty/x11/agent/tcpfwd/shell for channel */
1064 static void
1065 ssh_session2_setup(int id, void *arg)
1066 {
1067         extern char **environ;
1068         const char *display;
1069         int interactive = tty_flag;
1070
1071         display = getenv("DISPLAY");
1072         if (options.forward_x11 && display != NULL) {
1073                 char *proto, *data;
1074                 /* Get reasonable local authentication information. */
1075                 client_x11_get_proto(display, options.xauth_location,
1076                     options.forward_x11_trusted, &proto, &data);
1077                 /* Request forwarding with authentication spoofing. */
1078                 debug("Requesting X11 forwarding with authentication spoofing.");
1079                 x11_request_forwarding_with_spoofing(id, display, proto, data);
1080                 interactive = 1;
1081                 /* XXX wait for reply */
1082         }
1083
1084         check_agent_present();
1085         if (options.forward_agent) {
1086                 debug("Requesting authentication agent forwarding.");
1087                 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1088                 packet_send();
1089         }
1090
1091         if (options.tun_open != SSH_TUNMODE_NO) {
1092                 Channel *c;
1093                 int fd;
1094
1095                 debug("Requesting tun.");
1096                 if ((fd = tun_open(options.tun_local,
1097                     options.tun_open)) >= 0) {
1098                         c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1099                             CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1100                             0, "tun", 1);
1101                         c->datagram = 1;
1102 #if defined(SSH_TUN_FILTER)
1103                         if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1104                                 channel_register_filter(c->self, sys_tun_infilter,
1105                                     sys_tun_outfilter);
1106 #endif
1107                         packet_start(SSH2_MSG_CHANNEL_OPEN);
1108                         packet_put_cstring("tun@openssh.com");
1109                         packet_put_int(c->self);
1110                         packet_put_int(c->local_window_max);
1111                         packet_put_int(c->local_maxpacket);
1112                         packet_put_int(options.tun_open);
1113                         packet_put_int(options.tun_remote);
1114                         packet_send();
1115                 }
1116         }
1117
1118         client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1119             NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1120
1121         packet_set_interactive(interactive);
1122 }
1123
1124 /* open new channel for a session */
1125 static int
1126 ssh_session2_open(void)
1127 {
1128         Channel *c;
1129         int window, packetmax, in, out, err;
1130
1131         if (stdin_null_flag) {
1132                 in = open(_PATH_DEVNULL, O_RDONLY);
1133         } else {
1134                 in = dup(STDIN_FILENO);
1135         }
1136         out = dup(STDOUT_FILENO);
1137         err = dup(STDERR_FILENO);
1138
1139         if (in < 0 || out < 0 || err < 0)
1140                 fatal("dup() in/out/err failed");
1141
1142         /* enable nonblocking unless tty */
1143         if (!isatty(in))
1144                 set_nonblock(in);
1145         if (!isatty(out))
1146                 set_nonblock(out);
1147         if (!isatty(err))
1148                 set_nonblock(err);
1149
1150         window = CHAN_SES_WINDOW_DEFAULT;
1151         packetmax = CHAN_SES_PACKET_DEFAULT;
1152         if (tty_flag) {
1153                 window >>= 1;
1154                 packetmax >>= 1;
1155         }
1156         c = channel_new(
1157             "session", SSH_CHANNEL_OPENING, in, out, err,
1158             window, packetmax, CHAN_EXTENDED_WRITE,
1159             "client-session", /*nonblock*/0);
1160
1161         debug3("ssh_session2_open: channel_new: %d", c->self);
1162
1163         channel_send_open(c->self);
1164         if (!no_shell_flag)
1165                 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1166
1167         return c->self;
1168 }
1169
1170 static int
1171 ssh_session2(void)
1172 {
1173         int id = -1;
1174
1175         /* XXX should be pre-session */
1176         ssh_init_forwarding();
1177         ssh_control_listener();
1178
1179         if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1180                 id = ssh_session2_open();
1181
1182         /* Execute a local command */
1183         if (options.local_command != NULL &&
1184             options.permit_local_command)
1185                 ssh_local_cmd(options.local_command);
1186
1187         /* If requested, let ssh continue in the background. */
1188         if (fork_after_authentication_flag)
1189                 if (daemon(1, 1) < 0)
1190                         fatal("daemon() failed: %.200s", strerror(errno));
1191
1192         return client_loop(tty_flag, tty_flag ?
1193             options.escape_char : SSH_ESCAPECHAR_NONE, id);
1194 }
1195
1196 static void
1197 load_public_identity_files(void)
1198 {
1199         char *filename, *cp, thishost[NI_MAXHOST];
1200         int i = 0;
1201         Key *public;
1202         struct passwd *pw;
1203 #ifdef SMARTCARD
1204         Key **keys;
1205
1206         if (options.smartcard_device != NULL &&
1207             options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1208             (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1209                 int count = 0;
1210                 for (i = 0; keys[i] != NULL; i++) {
1211                         count++;
1212                         memmove(&options.identity_files[1], &options.identity_files[0],
1213                             sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1214                         memmove(&options.identity_keys[1], &options.identity_keys[0],
1215                             sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1216                         options.num_identity_files++;
1217                         options.identity_keys[0] = keys[i];
1218                         options.identity_files[0] = sc_get_key_label(keys[i]);
1219                 }
1220                 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1221                         options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1222                 i = count;
1223                 xfree(keys);
1224         }
1225 #endif /* SMARTCARD */
1226         if ((pw = getpwuid(original_real_uid)) == NULL)
1227                 fatal("load_public_identity_files: getpwuid failed");
1228         if (gethostname(thishost, sizeof(thishost)) == -1)
1229                 fatal("load_public_identity_files: gethostname: %s",
1230                     strerror(errno));
1231         for (; i < options.num_identity_files; i++) {
1232                 cp = tilde_expand_filename(options.identity_files[i],
1233                     original_real_uid);
1234                 filename = percent_expand(cp, "d", pw->pw_dir,
1235                     "u", pw->pw_name, "l", thishost, "h", host, 
1236                     "r", options.user, (char *)NULL);
1237                 xfree(cp);
1238                 public = key_load_public(filename, NULL);
1239                 debug("identity file %s type %d", filename,
1240                     public ? public->type : -1);
1241                 xfree(options.identity_files[i]);
1242                 options.identity_files[i] = filename;
1243                 options.identity_keys[i] = public;
1244         }
1245 }
1246
1247 static void
1248 control_client_sighandler(int signo)
1249 {
1250         control_client_terminate = signo;
1251 }
1252
1253 static void
1254 control_client_sigrelay(int signo)
1255 {
1256         if (control_server_pid > 1)
1257                 kill(control_server_pid, signo);
1258 }
1259
1260 static int
1261 env_permitted(char *env)
1262 {
1263         int i;
1264         char name[1024], *cp;
1265
1266         if (strlcpy(name, env, sizeof(name)) >= sizeof(name))
1267                 fatal("env_permitted: name too long");
1268         if ((cp = strchr(name, '=')) == NULL)
1269                 return (0);
1270
1271         *cp = '\0';
1272
1273         for (i = 0; i < options.num_send_env; i++)
1274                 if (match_pattern(name, options.send_env[i]))
1275                         return (1);
1276
1277         return (0);
1278 }
1279
1280 static void
1281 control_client(const char *path)
1282 {
1283         struct sockaddr_un addr;
1284         int i, r, fd, sock, exitval, num_env, addr_len;
1285         Buffer m;
1286         char *term;
1287         extern char **environ;
1288         u_int  flags;
1289
1290         if (mux_command == 0)
1291                 mux_command = SSHMUX_COMMAND_OPEN;
1292
1293         switch (options.control_master) {
1294         case SSHCTL_MASTER_AUTO:
1295         case SSHCTL_MASTER_AUTO_ASK:
1296                 debug("auto-mux: Trying existing master");
1297                 /* FALLTHROUGH */
1298         case SSHCTL_MASTER_NO:
1299                 break;
1300         default:
1301                 return;
1302         }
1303
1304         memset(&addr, '\0', sizeof(addr));
1305         addr.sun_family = AF_UNIX;
1306         addr_len = offsetof(struct sockaddr_un, sun_path) +
1307             strlen(path) + 1;
1308
1309         if (strlcpy(addr.sun_path, path,
1310             sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1311                 fatal("ControlPath too long");
1312
1313         if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1314                 fatal("%s socket(): %s", __func__, strerror(errno));
1315
1316         if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1317                 if (mux_command != SSHMUX_COMMAND_OPEN) {
1318                         fatal("Control socket connect(%.100s): %s", path,
1319                             strerror(errno));
1320                 }
1321                 if (errno == ENOENT)
1322                         debug("Control socket \"%.100s\" does not exist", path);
1323                 else {
1324                         error("Control socket connect(%.100s): %s", path,
1325                             strerror(errno));
1326                 }
1327                 close(sock);
1328                 return;
1329         }
1330
1331         if (stdin_null_flag) {
1332                 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1333                         fatal("open(/dev/null): %s", strerror(errno));
1334                 if (dup2(fd, STDIN_FILENO) == -1)
1335                         fatal("dup2: %s", strerror(errno));
1336                 if (fd > STDERR_FILENO)
1337                         close(fd);
1338         }
1339
1340         term = getenv("TERM");
1341
1342         flags = 0;
1343         if (tty_flag)
1344                 flags |= SSHMUX_FLAG_TTY;
1345         if (subsystem_flag)
1346                 flags |= SSHMUX_FLAG_SUBSYS;
1347         if (options.forward_x11)
1348                 flags |= SSHMUX_FLAG_X11_FWD;
1349         if (options.forward_agent)
1350                 flags |= SSHMUX_FLAG_AGENT_FWD;
1351
1352         buffer_init(&m);
1353
1354         /* Send our command to server */
1355         buffer_put_int(&m, mux_command);
1356         buffer_put_int(&m, flags);
1357         if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1358                 fatal("%s: msg_send", __func__);
1359         buffer_clear(&m);
1360
1361         /* Get authorisation status and PID of controlee */
1362         if (ssh_msg_recv(sock, &m) == -1)
1363                 fatal("%s: msg_recv", __func__);
1364         if (buffer_get_char(&m) != SSHMUX_VER)
1365                 fatal("%s: wrong version", __func__);
1366         if (buffer_get_int(&m) != 1)
1367                 fatal("Connection to master denied");
1368         control_server_pid = buffer_get_int(&m);
1369
1370         buffer_clear(&m);
1371
1372         switch (mux_command) {
1373         case SSHMUX_COMMAND_ALIVE_CHECK:
1374                 fprintf(stderr, "Master running (pid=%d)\r\n",
1375                     control_server_pid);
1376                 exit(0);
1377         case SSHMUX_COMMAND_TERMINATE:
1378                 fprintf(stderr, "Exit request sent.\r\n");
1379                 exit(0);
1380         case SSHMUX_COMMAND_OPEN:
1381                 /* continue below */
1382                 break;
1383         default:
1384                 fatal("silly mux_command %d", mux_command);
1385         }
1386
1387         /* SSHMUX_COMMAND_OPEN */
1388         buffer_put_cstring(&m, term ? term : "");
1389         buffer_append(&command, "\0", 1);
1390         buffer_put_cstring(&m, buffer_ptr(&command));
1391
1392         if (options.num_send_env == 0 || environ == NULL) {
1393                 buffer_put_int(&m, 0);
1394         } else {
1395                 /* Pass environment */
1396                 num_env = 0;
1397                 for (i = 0; environ[i] != NULL; i++)
1398                         if (env_permitted(environ[i]))
1399                                 num_env++; /* Count */
1400
1401                 buffer_put_int(&m, num_env);
1402
1403                 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1404                         if (env_permitted(environ[i])) {
1405                                 num_env--;
1406                                 buffer_put_cstring(&m, environ[i]);
1407                         }
1408         }
1409
1410         if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1411                 fatal("%s: msg_send", __func__);
1412
1413         mm_send_fd(sock, STDIN_FILENO);
1414         mm_send_fd(sock, STDOUT_FILENO);
1415         mm_send_fd(sock, STDERR_FILENO);
1416
1417         /* Wait for reply, so master has a chance to gather ttymodes */
1418         buffer_clear(&m);
1419         if (ssh_msg_recv(sock, &m) == -1)
1420                 fatal("%s: msg_recv", __func__);
1421         if (buffer_get_char(&m) != SSHMUX_VER)
1422                 fatal("%s: wrong version", __func__);
1423         buffer_free(&m);
1424
1425         signal(SIGHUP, control_client_sighandler);
1426         signal(SIGINT, control_client_sighandler);
1427         signal(SIGTERM, control_client_sighandler);
1428         signal(SIGWINCH, control_client_sigrelay);
1429
1430         if (tty_flag)
1431                 enter_raw_mode();
1432
1433         /* Stick around until the controlee closes the client_fd */
1434         exitval = 0;
1435         for (;!control_client_terminate;) {
1436                 r = read(sock, &exitval, sizeof(exitval));
1437                 if (r == 0) {
1438                         debug2("Received EOF from master");
1439                         break;
1440                 }
1441                 if (r > 0)
1442                         debug2("Received exit status from master %d", exitval);
1443                 if (r == -1 && errno != EINTR)
1444                         fatal("%s: read %s", __func__, strerror(errno));
1445         }
1446
1447         if (control_client_terminate)
1448                 debug2("Exiting on signal %d", control_client_terminate);
1449
1450         close(sock);
1451
1452         leave_raw_mode();
1453
1454         if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1455                 fprintf(stderr, "Connection to master closed.\r\n");
1456
1457         exit(exitval);
1458 }
This page took 0.158534 seconds and 5 git commands to generate.