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