]> andersk Git - openssh.git/blob - ssh.c
oops, this commit is really:
[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 RCSID("$OpenBSD: ssh.c,v 1.264 2006/02/20 17:19:54 stevesk Exp $");
44
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
48 #endif
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/un.h>
52
53 #include <paths.h>
54 #include <signal.h>
55
56 #include <openssl/evp.h>
57 #include <openssl/err.h>
58
59 #include "ssh.h"
60 #include "ssh1.h"
61 #include "ssh2.h"
62 #include "compat.h"
63 #include "cipher.h"
64 #include "xmalloc.h"
65 #include "packet.h"
66 #include "buffer.h"
67 #include "bufaux.h"
68 #include "channels.h"
69 #include "key.h"
70 #include "authfd.h"
71 #include "authfile.h"
72 #include "pathnames.h"
73 #include "dispatch.h"
74 #include "clientloop.h"
75 #include "log.h"
76 #include "readconf.h"
77 #include "sshconnect.h"
78 #include "misc.h"
79 #include "kex.h"
80 #include "mac.h"
81 #include "sshpty.h"
82 #include "match.h"
83 #include "msg.h"
84 #include "monitor_fdpass.h"
85 #include "uidswap.h"
86
87 #ifdef SMARTCARD
88 #include "scard.h"
89 #endif
90
91 extern char *__progname;
92
93 /* Flag indicating whether debug mode is on.  This can be set on the command line. */
94 int debug_flag = 0;
95
96 /* Flag indicating whether a tty should be allocated */
97 int tty_flag = 0;
98 int no_tty_flag = 0;
99 int force_tty_flag = 0;
100
101 /* don't exec a shell */
102 int no_shell_flag = 0;
103
104 /*
105  * Flag indicating that nothing should be read from stdin.  This can be set
106  * on the command line.
107  */
108 int stdin_null_flag = 0;
109
110 /*
111  * Flag indicating that ssh should fork after authentication.  This is useful
112  * so that the passphrase can be entered manually, and then ssh goes to the
113  * background.
114  */
115 int fork_after_authentication_flag = 0;
116
117 /*
118  * General data structure for command line options and options configurable
119  * in configuration files.  See readconf.h.
120  */
121 Options options;
122
123 /* optional user configfile */
124 char *config = NULL;
125
126 /*
127  * Name of the host we are connecting to.  This is the name given on the
128  * command line, or the HostName specified for the user-supplied name in a
129  * configuration file.
130  */
131 char *host;
132
133 /* socket address the host resolves to */
134 struct sockaddr_storage hostaddr;
135
136 /* Private host keys. */
137 Sensitive sensitive_data;
138
139 /* Original real UID. */
140 uid_t original_real_uid;
141 uid_t original_effective_uid;
142
143 /* command to be executed */
144 Buffer command;
145
146 /* Should we execute a command or invoke a subsystem? */
147 int subsystem_flag = 0;
148
149 /* # of replies received for global requests */
150 static int client_global_request_id = 0;
151
152 /* pid of proxycommand child process */
153 pid_t proxy_command_pid = 0;
154
155 /* fd to control socket */
156 int control_fd = -1;
157
158 /* Multiplexing control command */
159 static u_int mux_command = 0;
160
161 /* Only used in control client mode */
162 volatile sig_atomic_t control_client_terminate = 0;
163 u_int control_server_pid = 0;
164
165 /* Prints a help message to the user.  This function never returns. */
166
167 static void
168 usage(void)
169 {
170         fprintf(stderr,
171 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
172 "           [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
173 "           [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
174 "           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
175 "           [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
176 "           [-w tunnel:tunnel] [user@]hostname [command]\n"
177         );
178         exit(255);
179 }
180
181 static int ssh_session(void);
182 static int ssh_session2(void);
183 static void load_public_identity_files(void);
184 static void control_client(const char *path);
185
186 /*
187  * Main program for the ssh client.
188  */
189 int
190 main(int ac, char **av)
191 {
192         int i, opt, exit_status;
193         char *p, *cp, *line, buf[256];
194         struct stat st;
195         struct passwd *pw;
196         int dummy;
197         extern int optind, optreset;
198         extern char *optarg;
199         struct servent *sp;
200         Forward fwd;
201
202         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
203         sanitise_stdfd();
204
205         __progname = ssh_get_progname(av[0]);
206         init_rng();
207
208         /*
209          * Save the original real uid.  It will be needed later (uid-swapping
210          * may clobber the real uid).
211          */
212         original_real_uid = getuid();
213         original_effective_uid = geteuid();
214
215         /*
216          * Use uid-swapping to give up root privileges for the duration of
217          * option processing.  We will re-instantiate the rights when we are
218          * ready to create the privileged port, and will permanently drop
219          * them when the port has been created (actually, when the connection
220          * has been made, as we may need to create the port several times).
221          */
222         PRIV_END;
223
224 #ifdef HAVE_SETRLIMIT
225         /* If we are installed setuid root be careful to not drop core. */
226         if (original_real_uid != original_effective_uid) {
227                 struct rlimit rlim;
228                 rlim.rlim_cur = rlim.rlim_max = 0;
229                 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
230                         fatal("setrlimit failed: %.100s", strerror(errno));
231         }
232 #endif
233         /* Get user data. */
234         pw = getpwuid(original_real_uid);
235         if (!pw) {
236                 logit("You don't exist, go away!");
237                 exit(255);
238         }
239         /* Take a copy of the returned structure. */
240         pw = pwcopy(pw);
241
242         /*
243          * Set our umask to something reasonable, as some files are created
244          * with the default umask.  This will make them world-readable but
245          * writable only by the owner, which is ok for all files for which we
246          * don't set the modes explicitly.
247          */
248         umask(022);
249
250         /* Initialize option structure to indicate that no values have been set. */
251         initialize_options(&options);
252
253         /* Parse command-line arguments. */
254         host = NULL;
255
256 again:
257         while ((opt = getopt(ac, av,
258             "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
259                 switch (opt) {
260                 case '1':
261                         options.protocol = SSH_PROTO_1;
262                         break;
263                 case '2':
264                         options.protocol = SSH_PROTO_2;
265                         break;
266                 case '4':
267                         options.address_family = AF_INET;
268                         break;
269                 case '6':
270                         options.address_family = AF_INET6;
271                         break;
272                 case 'n':
273                         stdin_null_flag = 1;
274                         break;
275                 case 'f':
276                         fork_after_authentication_flag = 1;
277                         stdin_null_flag = 1;
278                         break;
279                 case 'x':
280                         options.forward_x11 = 0;
281                         break;
282                 case 'X':
283                         options.forward_x11 = 1;
284                         break;
285                 case 'Y':
286                         options.forward_x11 = 1;
287                         options.forward_x11_trusted = 1;
288                         break;
289                 case 'g':
290                         options.gateway_ports = 1;
291                         break;
292                 case 'O':
293                         if (strcmp(optarg, "check") == 0)
294                                 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
295                         else if (strcmp(optarg, "exit") == 0)
296                                 mux_command = SSHMUX_COMMAND_TERMINATE;
297                         else
298                                 fatal("Invalid multiplex command.");
299                         break;
300                 case 'P':       /* deprecated */
301                         options.use_privileged_port = 0;
302                         break;
303                 case 'a':
304                         options.forward_agent = 0;
305                         break;
306                 case 'A':
307                         options.forward_agent = 1;
308                         break;
309                 case 'k':
310                         options.gss_deleg_creds = 0;
311                         break;
312                 case 'i':
313                         if (stat(optarg, &st) < 0) {
314                                 fprintf(stderr, "Warning: Identity file %s "
315                                     "not accessible: %s.\n", optarg,
316                                     strerror(errno));
317                                 break;
318                         }
319                         if (options.num_identity_files >=
320                             SSH_MAX_IDENTITY_FILES)
321                                 fatal("Too many identity files specified "
322                                     "(max %d)", SSH_MAX_IDENTITY_FILES);
323                         options.identity_files[options.num_identity_files++] =
324                             xstrdup(optarg);
325                         break;
326                 case 'I':
327 #ifdef SMARTCARD
328                         options.smartcard_device = xstrdup(optarg);
329 #else
330                         fprintf(stderr, "no support for smartcards.\n");
331 #endif
332                         break;
333                 case 't':
334                         if (tty_flag)
335                                 force_tty_flag = 1;
336                         tty_flag = 1;
337                         break;
338                 case 'v':
339                         if (debug_flag == 0) {
340                                 debug_flag = 1;
341                                 options.log_level = SYSLOG_LEVEL_DEBUG1;
342                         } else {
343                                 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
344                                         options.log_level++;
345                                 break;
346                         }
347                         /* FALLTHROUGH */
348                 case 'V':
349                         fprintf(stderr, "%s, %s\n",
350                             SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
351                         if (opt == 'V')
352                                 exit(0);
353                         break;
354                 case 'w':
355                         if (options.tun_open == -1)
356                                 options.tun_open = SSH_TUNMODE_DEFAULT;
357                         options.tun_local = a2tun(optarg, &options.tun_remote);
358                         if (options.tun_local == SSH_TUNID_ERR) {
359                                 fprintf(stderr, "Bad tun device '%s'\n", optarg);
360                                 exit(255);
361                         }
362                         break;
363                 case 'q':
364                         options.log_level = SYSLOG_LEVEL_QUIET;
365                         break;
366                 case 'e':
367                         if (optarg[0] == '^' && optarg[2] == 0 &&
368                             (u_char) optarg[1] >= 64 &&
369                             (u_char) optarg[1] < 128)
370                                 options.escape_char = (u_char) optarg[1] & 31;
371                         else if (strlen(optarg) == 1)
372                                 options.escape_char = (u_char) optarg[0];
373                         else if (strcmp(optarg, "none") == 0)
374                                 options.escape_char = SSH_ESCAPECHAR_NONE;
375                         else {
376                                 fprintf(stderr, "Bad escape character '%s'.\n",
377                                     optarg);
378                                 exit(255);
379                         }
380                         break;
381                 case 'c':
382                         if (ciphers_valid(optarg)) {
383                                 /* SSH2 only */
384                                 options.ciphers = xstrdup(optarg);
385                                 options.cipher = SSH_CIPHER_INVALID;
386                         } else {
387                                 /* SSH1 only */
388                                 options.cipher = cipher_number(optarg);
389                                 if (options.cipher == -1) {
390                                         fprintf(stderr,
391                                             "Unknown cipher type '%s'\n",
392                                             optarg);
393                                         exit(255);
394                                 }
395                                 if (options.cipher == SSH_CIPHER_3DES)
396                                         options.ciphers = "3des-cbc";
397                                 else if (options.cipher == SSH_CIPHER_BLOWFISH)
398                                         options.ciphers = "blowfish-cbc";
399                                 else
400                                         options.ciphers = (char *)-1;
401                         }
402                         break;
403                 case 'm':
404                         if (mac_valid(optarg))
405                                 options.macs = xstrdup(optarg);
406                         else {
407                                 fprintf(stderr, "Unknown mac type '%s'\n",
408                                     optarg);
409                                 exit(255);
410                         }
411                         break;
412                 case 'M':
413                         if (options.control_master == SSHCTL_MASTER_YES)
414                                 options.control_master = SSHCTL_MASTER_ASK;
415                         else
416                                 options.control_master = SSHCTL_MASTER_YES;
417                         break;
418                 case 'p':
419                         options.port = a2port(optarg);
420                         if (options.port == 0) {
421                                 fprintf(stderr, "Bad port '%s'\n", optarg);
422                                 exit(255);
423                         }
424                         break;
425                 case 'l':
426                         options.user = optarg;
427                         break;
428
429                 case 'L':
430                         if (parse_forward(&fwd, optarg))
431                                 add_local_forward(&options, &fwd);
432                         else {
433                                 fprintf(stderr,
434                                     "Bad local forwarding specification '%s'\n",
435                                     optarg);
436                                 exit(255);
437                         }
438                         break;
439
440                 case 'R':
441                         if (parse_forward(&fwd, optarg)) {
442                                 add_remote_forward(&options, &fwd);
443                         } else {
444                                 fprintf(stderr,
445                                     "Bad remote forwarding specification "
446                                     "'%s'\n", optarg);
447                                 exit(255);
448                         }
449                         break;
450
451                 case 'D':
452                         cp = p = xstrdup(optarg);
453                         memset(&fwd, '\0', sizeof(fwd));
454                         fwd.connect_host = "socks";
455                         if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
456                                 fprintf(stderr, "Bad dynamic forwarding "
457                                     "specification '%.100s'\n", optarg);
458                                 exit(255);
459                         }
460                         if (cp != NULL) {
461                                 fwd.listen_port = a2port(cp);
462                                 fwd.listen_host = cleanhostname(fwd.listen_host);
463                         } else {
464                                 fwd.listen_port = a2port(fwd.listen_host);
465                                 fwd.listen_host = NULL;
466                         }
467
468                         if (fwd.listen_port == 0) {
469                                 fprintf(stderr, "Bad dynamic port '%s'\n",
470                                     optarg);
471                                 exit(255);
472                         }
473                         add_local_forward(&options, &fwd);
474                         xfree(p);
475                         break;
476
477                 case 'C':
478                         options.compression = 1;
479                         break;
480                 case 'N':
481                         no_shell_flag = 1;
482                         no_tty_flag = 1;
483                         break;
484                 case 'T':
485                         no_tty_flag = 1;
486                         break;
487                 case 'o':
488                         dummy = 1;
489                         line = xstrdup(optarg);
490                         if (process_config_line(&options, host ? host : "",
491                             line, "command-line", 0, &dummy) != 0)
492                                 exit(255);
493                         xfree(line);
494                         break;
495                 case 's':
496                         subsystem_flag = 1;
497                         break;
498                 case 'S':
499                         if (options.control_path != NULL)
500                                 free(options.control_path);
501                         options.control_path = xstrdup(optarg);
502                         break;
503                 case 'b':
504                         options.bind_address = optarg;
505                         break;
506                 case 'F':
507                         config = optarg;
508                         break;
509                 default:
510                         usage();
511                 }
512         }
513
514         ac -= optind;
515         av += optind;
516
517         if (ac > 0 && !host && **av != '-') {
518                 if (strrchr(*av, '@')) {
519                         p = xstrdup(*av);
520                         cp = strrchr(p, '@');
521                         if (cp == NULL || cp == p)
522                                 usage();
523                         options.user = p;
524                         *cp = '\0';
525                         host = ++cp;
526                 } else
527                         host = *av;
528                 if (ac > 1) {
529                         optind = optreset = 1;
530                         goto again;
531                 }
532                 ac--, av++;
533         }
534
535         /* Check that we got a host name. */
536         if (!host)
537                 usage();
538
539         SSLeay_add_all_algorithms();
540         ERR_load_crypto_strings();
541
542         /* Initialize the command to execute on remote host. */
543         buffer_init(&command);
544
545         /*
546          * Save the command to execute on the remote host in a buffer. There
547          * is no limit on the length of the command, except by the maximum
548          * packet size.  Also sets the tty flag if there is no command.
549          */
550         if (!ac) {
551                 /* No command specified - execute shell on a tty. */
552                 tty_flag = 1;
553                 if (subsystem_flag) {
554                         fprintf(stderr,
555                             "You must specify a subsystem to invoke.\n");
556                         usage();
557                 }
558         } else {
559                 /* A command has been specified.  Store it into the buffer. */
560                 for (i = 0; i < ac; i++) {
561                         if (i)
562                                 buffer_append(&command, " ", 1);
563                         buffer_append(&command, av[i], strlen(av[i]));
564                 }
565         }
566
567         /* Cannot fork to background if no command. */
568         if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
569                 fatal("Cannot fork into background without a command to execute.");
570
571         /* Allocate a tty by default if no command specified. */
572         if (buffer_len(&command) == 0)
573                 tty_flag = 1;
574
575         /* Force no tty */
576         if (no_tty_flag)
577                 tty_flag = 0;
578         /* Do not allocate a tty if stdin is not a tty. */
579         if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
580                 if (tty_flag)
581                         logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
582                 tty_flag = 0;
583         }
584
585         /*
586          * Initialize "log" output.  Since we are the client all output
587          * actually goes to stderr.
588          */
589         log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
590             SYSLOG_FACILITY_USER, 1);
591
592         /*
593          * Read per-user configuration file.  Ignore the system wide config
594          * file if the user specifies a config file on the command line.
595          */
596         if (config != NULL) {
597                 if (!read_config_file(config, host, &options, 0))
598                         fatal("Can't open user config file %.100s: "
599                             "%.100s", config, strerror(errno));
600         } else  {
601                 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
602                     _PATH_SSH_USER_CONFFILE);
603                 (void)read_config_file(buf, host, &options, 1);
604
605                 /* Read systemwide configuration file after use config. */
606                 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
607                     &options, 0);
608         }
609
610         /* Fill configuration defaults. */
611         fill_default_options(&options);
612
613         channel_set_af(options.address_family);
614
615         /* reinit */
616         log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
617
618         seed_rng();
619
620         if (options.user == NULL)
621                 options.user = xstrdup(pw->pw_name);
622
623         if (options.hostname != NULL)
624                 host = options.hostname;
625
626         /* force lowercase for hostkey matching */
627         if (options.host_key_alias != NULL) {
628                 for (p = options.host_key_alias; *p; p++)
629                         if (isupper(*p))
630                                 *p = tolower(*p);
631         }
632
633         /* Get default port if port has not been set. */
634         if (options.port == 0) {
635                 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
636                 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
637         }
638
639         if (options.proxy_command != NULL &&
640             strcmp(options.proxy_command, "none") == 0)
641                 options.proxy_command = NULL;
642         if (options.control_path != NULL &&
643             strcmp(options.control_path, "none") == 0)
644                 options.control_path = NULL;
645
646         if (options.control_path != NULL) {
647                 char me[NI_MAXHOST];
648
649                 if (gethostname(me, sizeof(me)) == -1)
650                         fatal("gethostname: %s", strerror(errno));
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, "l", me, (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 >>= 1;
1149                 packetmax >>= 1;
1150         }
1151         c = channel_new(
1152             "session", SSH_CHANNEL_OPENING, in, out, err,
1153             window, packetmax, CHAN_EXTENDED_WRITE,
1154             "client-session", /*nonblock*/0);
1155
1156         debug3("ssh_session2_open: channel_new: %d", c->self);
1157
1158         channel_send_open(c->self);
1159         if (!no_shell_flag)
1160                 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1161
1162         return c->self;
1163 }
1164
1165 static int
1166 ssh_session2(void)
1167 {
1168         int id = -1;
1169
1170         /* XXX should be pre-session */
1171         ssh_init_forwarding();
1172         ssh_control_listener();
1173
1174         if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1175                 id = ssh_session2_open();
1176
1177         /* Execute a local command */
1178         if (options.local_command != NULL &&
1179             options.permit_local_command)
1180                 ssh_local_cmd(options.local_command);
1181
1182         /* If requested, let ssh continue in the background. */
1183         if (fork_after_authentication_flag)
1184                 if (daemon(1, 1) < 0)
1185                         fatal("daemon() failed: %.200s", strerror(errno));
1186
1187         return client_loop(tty_flag, tty_flag ?
1188             options.escape_char : SSH_ESCAPECHAR_NONE, id);
1189 }
1190
1191 static void
1192 load_public_identity_files(void)
1193 {
1194         char *filename;
1195         int i = 0;
1196         Key *public;
1197 #ifdef SMARTCARD
1198         Key **keys;
1199
1200         if (options.smartcard_device != NULL &&
1201             options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1202             (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1203                 int count = 0;
1204                 for (i = 0; keys[i] != NULL; i++) {
1205                         count++;
1206                         memmove(&options.identity_files[1], &options.identity_files[0],
1207                             sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1208                         memmove(&options.identity_keys[1], &options.identity_keys[0],
1209                             sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1210                         options.num_identity_files++;
1211                         options.identity_keys[0] = keys[i];
1212                         options.identity_files[0] = sc_get_key_label(keys[i]);
1213                 }
1214                 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1215                         options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1216                 i = count;
1217                 xfree(keys);
1218         }
1219 #endif /* SMARTCARD */
1220         for (; i < options.num_identity_files; i++) {
1221                 filename = tilde_expand_filename(options.identity_files[i],
1222                     original_real_uid);
1223                 public = key_load_public(filename, NULL);
1224                 debug("identity file %s type %d", filename,
1225                     public ? public->type : -1);
1226                 xfree(options.identity_files[i]);
1227                 options.identity_files[i] = filename;
1228                 options.identity_keys[i] = public;
1229         }
1230 }
1231
1232 static void
1233 control_client_sighandler(int signo)
1234 {
1235         control_client_terminate = signo;
1236 }
1237
1238 static void
1239 control_client_sigrelay(int signo)
1240 {
1241         if (control_server_pid > 1)
1242                 kill(control_server_pid, signo);
1243 }
1244
1245 static int
1246 env_permitted(char *env)
1247 {
1248         int i;
1249         char name[1024], *cp;
1250
1251         strlcpy(name, env, sizeof(name));
1252         if ((cp = strchr(name, '=')) == NULL)
1253                 return (0);
1254
1255         *cp = '\0';
1256
1257         for (i = 0; i < options.num_send_env; i++)
1258                 if (match_pattern(name, options.send_env[i]))
1259                         return (1);
1260
1261         return (0);
1262 }
1263
1264 static void
1265 control_client(const char *path)
1266 {
1267         struct sockaddr_un addr;
1268         int i, r, fd, sock, exitval, num_env, addr_len;
1269         Buffer m;
1270         char *term;
1271         extern char **environ;
1272         u_int  flags;
1273
1274         if (mux_command == 0)
1275                 mux_command = SSHMUX_COMMAND_OPEN;
1276
1277         switch (options.control_master) {
1278         case SSHCTL_MASTER_AUTO:
1279         case SSHCTL_MASTER_AUTO_ASK:
1280                 debug("auto-mux: Trying existing master");
1281                 /* FALLTHROUGH */
1282         case SSHCTL_MASTER_NO:
1283                 break;
1284         default:
1285                 return;
1286         }
1287
1288         memset(&addr, '\0', sizeof(addr));
1289         addr.sun_family = AF_UNIX;
1290         addr_len = offsetof(struct sockaddr_un, sun_path) +
1291             strlen(path) + 1;
1292
1293         if (strlcpy(addr.sun_path, path,
1294             sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1295                 fatal("ControlPath too long");
1296
1297         if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1298                 fatal("%s socket(): %s", __func__, strerror(errno));
1299
1300         if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1301                 if (mux_command != SSHMUX_COMMAND_OPEN) {
1302                         fatal("Control socket connect(%.100s): %s", path,
1303                             strerror(errno));
1304                 }
1305                 if (errno == ENOENT)
1306                         debug("Control socket \"%.100s\" does not exist", path);
1307                 else {
1308                         error("Control socket connect(%.100s): %s", path,
1309                             strerror(errno));
1310                 }
1311                 close(sock);
1312                 return;
1313         }
1314
1315         if (stdin_null_flag) {
1316                 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1317                         fatal("open(/dev/null): %s", strerror(errno));
1318                 if (dup2(fd, STDIN_FILENO) == -1)
1319                         fatal("dup2: %s", strerror(errno));
1320                 if (fd > STDERR_FILENO)
1321                         close(fd);
1322         }
1323
1324         term = getenv("TERM");
1325
1326         flags = 0;
1327         if (tty_flag)
1328                 flags |= SSHMUX_FLAG_TTY;
1329         if (subsystem_flag)
1330                 flags |= SSHMUX_FLAG_SUBSYS;
1331         if (options.forward_x11)
1332                 flags |= SSHMUX_FLAG_X11_FWD;
1333         if (options.forward_agent)
1334                 flags |= SSHMUX_FLAG_AGENT_FWD;
1335
1336         buffer_init(&m);
1337
1338         /* Send our command to server */
1339         buffer_put_int(&m, mux_command);
1340         buffer_put_int(&m, flags);
1341         if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1342                 fatal("%s: msg_send", __func__);
1343         buffer_clear(&m);
1344
1345         /* Get authorisation status and PID of controlee */
1346         if (ssh_msg_recv(sock, &m) == -1)
1347                 fatal("%s: msg_recv", __func__);
1348         if (buffer_get_char(&m) != SSHMUX_VER)
1349                 fatal("%s: wrong version", __func__);
1350         if (buffer_get_int(&m) != 1)
1351                 fatal("Connection to master denied");
1352         control_server_pid = buffer_get_int(&m);
1353
1354         buffer_clear(&m);
1355
1356         switch (mux_command) {
1357         case SSHMUX_COMMAND_ALIVE_CHECK:
1358                 fprintf(stderr, "Master running (pid=%d)\r\n",
1359                     control_server_pid);
1360                 exit(0);
1361         case SSHMUX_COMMAND_TERMINATE:
1362                 fprintf(stderr, "Exit request sent.\r\n");
1363                 exit(0);
1364         case SSHMUX_COMMAND_OPEN:
1365                 /* continue below */
1366                 break;
1367         default:
1368                 fatal("silly mux_command %d", mux_command);
1369         }
1370
1371         /* SSHMUX_COMMAND_OPEN */
1372         buffer_put_cstring(&m, term ? term : "");
1373         buffer_append(&command, "\0", 1);
1374         buffer_put_cstring(&m, buffer_ptr(&command));
1375
1376         if (options.num_send_env == 0 || environ == NULL) {
1377                 buffer_put_int(&m, 0);
1378         } else {
1379                 /* Pass environment */
1380                 num_env = 0;
1381                 for (i = 0; environ[i] != NULL; i++)
1382                         if (env_permitted(environ[i]))
1383                                 num_env++; /* Count */
1384
1385                 buffer_put_int(&m, num_env);
1386
1387                 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1388                         if (env_permitted(environ[i])) {
1389                                 num_env--;
1390                                 buffer_put_cstring(&m, environ[i]);
1391                         }
1392         }
1393
1394         if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1395                 fatal("%s: msg_send", __func__);
1396
1397         mm_send_fd(sock, STDIN_FILENO);
1398         mm_send_fd(sock, STDOUT_FILENO);
1399         mm_send_fd(sock, STDERR_FILENO);
1400
1401         /* Wait for reply, so master has a chance to gather ttymodes */
1402         buffer_clear(&m);
1403         if (ssh_msg_recv(sock, &m) == -1)
1404                 fatal("%s: msg_recv", __func__);
1405         if (buffer_get_char(&m) != SSHMUX_VER)
1406                 fatal("%s: wrong version", __func__);
1407         buffer_free(&m);
1408
1409         signal(SIGHUP, control_client_sighandler);
1410         signal(SIGINT, control_client_sighandler);
1411         signal(SIGTERM, control_client_sighandler);
1412         signal(SIGWINCH, control_client_sigrelay);
1413
1414         if (tty_flag)
1415                 enter_raw_mode();
1416
1417         /* Stick around until the controlee closes the client_fd */
1418         exitval = 0;
1419         for (;!control_client_terminate;) {
1420                 r = read(sock, &exitval, sizeof(exitval));
1421                 if (r == 0) {
1422                         debug2("Received EOF from master");
1423                         break;
1424                 }
1425                 if (r > 0)
1426                         debug2("Received exit status from master %d", exitval);
1427                 if (r == -1 && errno != EINTR)
1428                         fatal("%s: read %s", __func__, strerror(errno));
1429         }
1430
1431         if (control_client_terminate)
1432                 debug2("Exiting on signal %d", control_client_terminate);
1433
1434         close(sock);
1435
1436         leave_raw_mode();
1437
1438         if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1439                 fprintf(stderr, "Connection to master closed.\r\n");
1440
1441         exit(exitval);
1442 }
This page took 2.503766 seconds and 5 git commands to generate.