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