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