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