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