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