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