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