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