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