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