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