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