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