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