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