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