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