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