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