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