]> andersk Git - openssh.git/blame - ssh.c
- djm@cvs.openbsd.org 2004/06/17 15:10:14
[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"
0d34d6ce 43RCSID("$OpenBSD: ssh.c,v 1.216 2004/06/17 15:10:14 djm 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,
160"usage: ssh [-1246AaCfghkNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
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"
163" [-p port] [-R port:host:hostport] [user@]hostname [command]\n"
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':
379 options.control_master = 1;
380 break;
5260325f 381 case 'p':
2d2a2c65 382 options.port = a2port(optarg);
383 if (options.port == 0) {
6031af8d 384 fprintf(stderr, "Bad port '%s'\n", optarg);
385 exit(1);
386 }
5260325f 387 break;
5260325f 388 case 'l':
389 options.user = optarg;
390 break;
d2e3df16 391
392 case 'L':
5260325f 393 case 'R':
fa065de2 394 if (sscanf(optarg, "%5[0123456789]:%255[^:]:%5[0123456789]",
d2e3df16 395 sfwd_port, buf, sfwd_host_port) != 3 &&
fa065de2 396 sscanf(optarg, "%5[0123456789]/%255[^/]/%5[0123456789]",
d2e3df16 397 sfwd_port, buf, sfwd_host_port) != 3) {
f5a1a01a 398 fprintf(stderr,
d2e3df16 399 "Bad forwarding specification '%s'\n",
f5a1a01a 400 optarg);
5260325f 401 usage();
402 /* NOTREACHED */
403 }
d2e3df16 404 if ((fwd_port = a2port(sfwd_port)) == 0 ||
762715ce 405 (fwd_host_port = a2port(sfwd_host_port)) == 0) {
f5a1a01a 406 fprintf(stderr,
d2e3df16 407 "Bad forwarding port(s) '%s'\n", optarg);
408 exit(1);
5260325f 409 }
d2e3df16 410 if (opt == 'L')
411 add_local_forward(&options, fwd_port, buf,
412 fwd_host_port);
413 else if (opt == 'R')
414 add_remote_forward(&options, fwd_port, buf,
184eed6a 415 fwd_host_port);
5260325f 416 break;
0490e609 417
418 case 'D':
2d2a2c65 419 fwd_port = a2port(optarg);
420 if (fwd_port == 0) {
f5a1a01a 421 fprintf(stderr, "Bad dynamic port '%s'\n",
422 optarg);
6031af8d 423 exit(1);
424 }
37ba5172 425 add_local_forward(&options, fwd_port, "socks", 0);
0490e609 426 break;
427
5260325f 428 case 'C':
429 options.compression = 1;
430 break;
8ce64345 431 case 'N':
432 no_shell_flag = 1;
433 no_tty_flag = 1;
434 break;
8ce64345 435 case 'T':
436 no_tty_flag = 1;
437 break;
5260325f 438 case 'o':
439 dummy = 1;
1aafd17a 440 line = xstrdup(optarg);
f5a1a01a 441 if (process_config_line(&options, host ? host : "",
1aafd17a 442 line, "command-line", 0, &dummy) != 0)
5260325f 443 exit(1);
1aafd17a 444 xfree(line);
5260325f 445 break;
ae810de7 446 case 's':
447 subsystem_flag = 1;
448 break;
5e96b616 449 case 'S':
450 if (options.control_path != NULL)
451 free(options.control_path);
452 options.control_path = xstrdup(optarg);
453 if (options.control_master == -1)
454 options.control_master = 0;
455 break;
3435f5a6 456 case 'b':
457 options.bind_address = optarg;
458 break;
e591b98a 459 case 'F':
460 config = optarg;
461 break;
5260325f 462 default:
463 usage();
464 }
465 }
466
f5a1a01a 467 ac -= optind;
468 av += optind;
469
470 if (ac > 0 && !host && **av != '-') {
15748b4d 471 if (strrchr(*av, '@')) {
f5a1a01a 472 p = xstrdup(*av);
15748b4d 473 cp = strrchr(p, '@');
f5a1a01a 474 if (cp == NULL || cp == p)
475 usage();
476 options.user = p;
477 *cp = '\0';
478 host = ++cp;
479 } else
480 host = *av;
978ebf99 481 if (ac > 1) {
482 optind = optreset = 1;
f5a1a01a 483 goto again;
484 }
978ebf99 485 ac--, av++;
f5a1a01a 486 }
487
5260325f 488 /* Check that we got a host name. */
489 if (!host)
8efc0c15 490 usage();
5260325f 491
22d89d24 492 SSLeay_add_all_algorithms();
fa08c86b 493 ERR_load_crypto_strings();
22d89d24 494
5260325f 495 /* Initialize the command to execute on remote host. */
496 buffer_init(&command);
497
aa3378df 498 /*
499 * Save the command to execute on the remote host in a buffer. There
500 * is no limit on the length of the command, except by the maximum
501 * packet size. Also sets the tty flag if there is no command.
502 */
f5a1a01a 503 if (!ac) {
5260325f 504 /* No command specified - execute shell on a tty. */
505 tty_flag = 1;
ae810de7 506 if (subsystem_flag) {
f5a1a01a 507 fprintf(stderr,
508 "You must specify a subsystem to invoke.\n");
ae810de7 509 usage();
510 }
5260325f 511 } else {
f5a1a01a 512 /* A command has been specified. Store it into the buffer. */
513 for (i = 0; i < ac; i++) {
514 if (i)
5260325f 515 buffer_append(&command, " ", 1);
516 buffer_append(&command, av[i], strlen(av[i]));
517 }
8efc0c15 518 }
5260325f 519
520 /* Cannot fork to background if no command. */
14a9a859 521 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
5260325f 522 fatal("Cannot fork into background without a command to execute.");
523
524 /* Allocate a tty by default if no command specified. */
525 if (buffer_len(&command) == 0)
526 tty_flag = 1;
527
343288b8 528 /* Force no tty */
0b6fbf03 529 if (no_tty_flag)
530 tty_flag = 0;
5260325f 531 /* Do not allocate a tty if stdin is not a tty. */
8abcdba4 532 if (!isatty(fileno(stdin)) && !force_tty_flag) {
5260325f 533 if (tty_flag)
bbe88b6d 534 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
5260325f 535 tty_flag = 0;
536 }
8ce64345 537
20244695 538 /*
539 * Initialize "log" output. Since we are the client all output
540 * actually goes to stderr.
541 */
cc44f691 542 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
543 SYSLOG_FACILITY_USER, 1);
5260325f 544
e591b98a 545 /*
546 * Read per-user configuration file. Ignore the system wide config
547 * file if the user specifies a config file on the command line.
548 */
549 if (config != NULL) {
f7f14143 550 if (!read_config_file(config, host, &options, 0))
93111dfa 551 fatal("Can't open user config file %.100s: "
552 "%.100s", config, strerror(errno));
e591b98a 553 } else {
554 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
555 _PATH_SSH_USER_CONFFILE);
9f6cab4b 556 (void)read_config_file(buf, host, &options, 1);
e591b98a 557
f67792f2 558 /* Read systemwide configuration file after use config. */
9f6cab4b 559 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
560 &options, 0);
e591b98a 561 }
5260325f 562
563 /* Fill configuration defaults. */
564 fill_default_options(&options);
565
1572b90f 566 channel_set_af(options.address_family);
567
5260325f 568 /* reinit */
20244695 569 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
5260325f 570
e339aa53 571 seed_rng();
572
5260325f 573 if (options.user == NULL)
574 options.user = xstrdup(pw->pw_name);
575
576 if (options.hostname != NULL)
577 host = options.hostname;
578
03c82656 579 /* force lowercase for hostkey matching */
580 if (options.host_key_alias != NULL) {
581 for (p = options.host_key_alias; *p; p++)
582 if (isupper(*p))
583 *p = tolower(*p);
584 }
585
f78bde70 586 if (options.proxy_command != NULL &&
587 strcmp(options.proxy_command, "none") == 0)
588 options.proxy_command = NULL;
589
5e96b616 590 if (options.control_path != NULL) {
591 options.control_path = tilde_expand_filename(
592 options.control_path, original_real_uid);
593 }
594 if (options.control_path != NULL && options.control_master == 0)
595 control_client(options.control_path); /* This doesn't return */
596
6ffc9c88 597 /* Open a connection to the remote host. */
1572b90f 598 if (ssh_connect(host, &hostaddr, options.port,
599 options.address_family, options.connection_attempts,
d514c907 600#ifdef HAVE_CYGWIN
601 options.use_privileged_port,
602#else
3fb156df 603 original_effective_uid == 0 && options.use_privileged_port,
d514c907 604#endif
de60473e 605 options.proxy_command) != 0)
b34bec32 606 exit(1);
5260325f 607
aa3378df 608 /*
609 * If we successfully made the connection, load the host private key
610 * in case we will need it later for combined rsa-rhosts
611 * authentication. This must be done before releasing extra
612 * privileges, because the file is only readable by root.
78660ed4 613 * If we cannot access the private keys, load the public keys
614 * instead and try to execute the ssh-keysign helper instead.
aa3378df 615 */
8002af61 616 sensitive_data.nkeys = 0;
617 sensitive_data.keys = NULL;
39c00dc2 618 sensitive_data.external_keysign = 0;
b34bec32 619 if (options.rhosts_rsa_authentication ||
620 options.hostbased_authentication) {
8002af61 621 sensitive_data.nkeys = 3;
343288b8 622 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
623 sizeof(Key));
3fb156df 624
625 PRIV_START;
8002af61 626 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
aeaa3d9e 627 _PATH_HOST_KEY_FILE, "", NULL);
8002af61 628 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
629 _PATH_HOST_DSA_KEY_FILE, "", NULL);
630 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
631 _PATH_HOST_RSA_KEY_FILE, "", NULL);
3fb156df 632 PRIV_END;
39c00dc2 633
60cd0a97 634 if (options.hostbased_authentication == 1 &&
635 sensitive_data.keys[0] == NULL &&
39c00dc2 636 sensitive_data.keys[1] == NULL &&
637 sensitive_data.keys[2] == NULL) {
638 sensitive_data.keys[1] = key_load_public(
639 _PATH_HOST_DSA_KEY_FILE, NULL);
640 sensitive_data.keys[2] = key_load_public(
641 _PATH_HOST_RSA_KEY_FILE, NULL);
642 sensitive_data.external_keysign = 1;
643 }
5260325f 644 }
aa3378df 645 /*
646 * Get rid of any extra privileges that we may have. We will no
647 * longer need them. Also, extra privileges could make it very hard
648 * to read identity files and other non-world-readable files from the
649 * user's home directory if it happens to be on a NFS volume where
650 * root is mapped to nobody.
651 */
3fb156df 652 seteuid(original_real_uid);
653 setuid(original_real_uid);
5260325f 654
aa3378df 655 /*
656 * Now that we are back to our own permissions, create ~/.ssh
657 * directory if it doesn\'t already exist.
658 */
c3abff07 659 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
5260325f 660 if (stat(buf, &st) < 0)
704b1659 661 if (mkdir(buf, 0700) < 0)
5260325f 662 error("Could not create directory '%.200s'.", buf);
663
fee56204 664 /* load options.identity_files */
665 load_public_identity_files();
666
667 /* Expand ~ in known host file names. */
668 /* XXX mem-leaks: */
fa08c86b 669 options.system_hostfile =
670 tilde_expand_filename(options.system_hostfile, original_real_uid);
671 options.user_hostfile =
672 tilde_expand_filename(options.user_hostfile, original_real_uid);
673 options.system_hostfile2 =
674 tilde_expand_filename(options.system_hostfile2, original_real_uid);
675 options.user_hostfile2 =
676 tilde_expand_filename(options.user_hostfile2, original_real_uid);
5260325f 677
67b75437 678 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
679
5260325f 680 /* Log into the remote system. This never returns if the login fails. */
39c00dc2 681 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
8002af61 682
683 /* We no longer need the private host keys. Clear them now. */
684 if (sensitive_data.nkeys != 0) {
685 for (i = 0; i < sensitive_data.nkeys; i++) {
686 if (sensitive_data.keys[i] != NULL) {
687 /* Destroys contents safely */
688 debug3("clear hostkey %d", i);
689 key_free(sensitive_data.keys[i]);
690 sensitive_data.keys[i] = NULL;
691 }
692 }
693 xfree(sensitive_data.keys);
694 }
05b7537a 695 for (i = 0; i < options.num_identity_files; i++) {
696 if (options.identity_files[i]) {
697 xfree(options.identity_files[i]);
698 options.identity_files[i] = NULL;
699 }
700 if (options.identity_keys[i]) {
701 key_free(options.identity_keys[i]);
702 options.identity_keys[i] = NULL;
703 }
704 }
5260325f 705
8ce64345 706 exit_status = compat20 ? ssh_session2() : ssh_session();
707 packet_close();
6939bbd4 708
5e96b616 709 if (options.control_path != NULL && control_fd != -1)
710 unlink(options.control_path);
711
6939bbd4 712 /*
aff51935 713 * Send SIGHUP to proxy command if used. We don't wait() in
6939bbd4 714 * case it hangs and instead rely on init to reap the child
715 */
716 if (proxy_command_pid > 1)
717 kill(proxy_command_pid, SIGHUP);
718
8ce64345 719 return exit_status;
720}
721
d73a67d7 722#define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
723
396c147e 724static void
b48eeb07 725x11_get_proto(char **_proto, char **_data)
0b242b12 726{
d73a67d7 727 char cmd[1024];
0b242b12 728 char line[512];
d73a67d7 729 char xdisplay[512];
b48eeb07 730 static char proto[512], data[512];
0b242b12 731 FILE *f;
d73a67d7 732 int got_data = 0, generated = 0, do_unlink = 0, i;
733 char *display, *xauthdir, *xauthfile;
5d185586 734 struct stat st;
0b242b12 735
d73a67d7 736 xauthdir = xauthfile = NULL;
b48eeb07 737 *_proto = proto;
738 *_data = data;
739 proto[0] = data[0] = '\0';
d73a67d7 740
5d185586 741 if (!options.xauth_location ||
742 (stat(options.xauth_location, &st) == -1)) {
743 debug("No xauth program.");
744 } else {
745 if ((display = getenv("DISPLAY")) == NULL) {
746 debug("x11_get_proto: DISPLAY not set");
747 return;
748 }
d73a67d7 749 /*
750 * Handle FamilyLocal case where $DISPLAY does
751 * not match an authorization entry. For this we
752 * just try "xauth list unix:displaynum.screennum".
753 * XXX: "localhost" match to determine FamilyLocal
754 * is not perfect.
755 */
756 if (strncmp(display, "localhost:", 10) == 0) {
757 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
758 display + 10);
759 display = xdisplay;
760 }
761 if (options.forward_x11_trusted == 0) {
762 xauthdir = xmalloc(MAXPATHLEN);
763 xauthfile = xmalloc(MAXPATHLEN);
764 strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
765 if (mkdtemp(xauthdir) != NULL) {
766 do_unlink = 1;
767 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
768 xauthdir);
769 snprintf(cmd, sizeof(cmd),
770 "%s -f %s generate %s " SSH_X11_PROTO
c876ee7e 771 " untrusted timeout 1200 2>" _PATH_DEVNULL,
d73a67d7 772 options.xauth_location, xauthfile, display);
773 debug2("x11_get_proto: %s", cmd);
774 if (system(cmd) == 0)
775 generated = 1;
776 }
777 }
778 snprintf(cmd, sizeof(cmd),
779 "%s %s%s list %s . 2>" _PATH_DEVNULL,
780 options.xauth_location,
781 generated ? "-f " : "" ,
782 generated ? xauthfile : "",
783 display);
784 debug2("x11_get_proto: %s", cmd);
785 f = popen(cmd, "r");
fa649821 786 if (f && fgets(line, sizeof(line), f) &&
b48eeb07 787 sscanf(line, "%*s %511s %511s", proto, data) == 2)
fa649821 788 got_data = 1;
789 if (f)
790 pclose(f);
791 }
d73a67d7 792
793 if (do_unlink) {
794 unlink(xauthfile);
795 rmdir(xauthdir);
796 }
797 if (xauthdir)
798 xfree(xauthdir);
799 if (xauthfile)
800 xfree(xauthfile);
801
0b242b12 802 /*
803 * If we didn't get authentication data, just make up some
804 * data. The forwarding code will check the validity of the
805 * response anyway, and substitute this data. The X11
806 * server, however, will ignore this fake data and use
807 * whatever authentication mechanisms it was using otherwise
808 * for the local connection.
809 */
810 if (!got_data) {
811 u_int32_t rand = 0;
812
d73a67d7 813 logit("Warning: No xauth data; "
814 "using fake authentication data for X11 forwarding.");
815 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
0b242b12 816 for (i = 0; i < 16; i++) {
817 if (i % 4 == 0)
818 rand = arc4random();
d73a67d7 819 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
820 rand & 0xff);
0b242b12 821 rand >>= 8;
822 }
823 }
824}
825
396c147e 826static void
fa08c86b 827ssh_init_forwarding(void)
828{
02a024dd 829 int success = 0;
fa08c86b 830 int i;
02a024dd 831
fa08c86b 832 /* Initiate local TCP/IP port forwardings. */
833 for (i = 0; i < options.num_local_forwards; i++) {
834 debug("Connections to local port %d forwarded to remote address %.200s:%d",
835 options.local_forwards[i].port,
836 options.local_forwards[i].host,
837 options.local_forwards[i].host_port);
5641aefa 838 success += channel_setup_local_fwd_listener(
fa08c86b 839 options.local_forwards[i].port,
840 options.local_forwards[i].host,
841 options.local_forwards[i].host_port,
842 options.gateway_ports);
843 }
02a024dd 844 if (i > 0 && success == 0)
845 error("Could not request local forwarding.");
fa08c86b 846
847 /* Initiate remote TCP/IP port forwardings. */
848 for (i = 0; i < options.num_remote_forwards; i++) {
849 debug("Connections to remote port %d forwarded to local address %.200s:%d",
850 options.remote_forwards[i].port,
851 options.remote_forwards[i].host,
852 options.remote_forwards[i].host_port);
853 channel_request_remote_forwarding(
854 options.remote_forwards[i].port,
855 options.remote_forwards[i].host,
856 options.remote_forwards[i].host_port);
857 }
858}
859
396c147e 860static void
fa08c86b 861check_agent_present(void)
862{
863 if (options.forward_agent) {
864 /* Clear agent forwarding if we don\'t have an agent. */
8b10e20e 865 if (!ssh_agent_present())
fa08c86b 866 options.forward_agent = 0;
fa08c86b 867 }
868}
869
396c147e 870static int
8ce64345 871ssh_session(void)
872{
873 int type;
8ce64345 874 int interactive = 0;
875 int have_tty = 0;
876 struct winsize ws;
8ce64345 877 char *cp;
878
5260325f 879 /* Enable compression if requested. */
880 if (options.compression) {
881 debug("Requesting compression at level %d.", options.compression_level);
882
883 if (options.compression_level < 1 || options.compression_level > 9)
884 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
885
886 /* Send the request. */
887 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
888 packet_put_int(options.compression_level);
889 packet_send();
890 packet_write_wait();
54a5250f 891 type = packet_read();
5260325f 892 if (type == SSH_SMSG_SUCCESS)
893 packet_start_compression(options.compression_level);
894 else if (type == SSH_SMSG_FAILURE)
bbe88b6d 895 logit("Warning: Remote host refused compression.");
5260325f 896 else
897 packet_disconnect("Protocol error waiting for compression response.");
898 }
899 /* Allocate a pseudo tty if appropriate. */
900 if (tty_flag) {
901 debug("Requesting pty.");
902
903 /* Start the packet. */
904 packet_start(SSH_CMSG_REQUEST_PTY);
905
906 /* Store TERM in the packet. There is no limit on the
907 length of the string. */
908 cp = getenv("TERM");
909 if (!cp)
910 cp = "";
449c5ba5 911 packet_put_cstring(cp);
5260325f 912
913 /* Store window size in the packet. */
914 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
915 memset(&ws, 0, sizeof(ws));
916 packet_put_int(ws.ws_row);
917 packet_put_int(ws.ws_col);
918 packet_put_int(ws.ws_xpixel);
919 packet_put_int(ws.ws_ypixel);
920
921 /* Store tty modes in the packet. */
30dcc918 922 tty_make_modes(fileno(stdin), NULL);
5260325f 923
924 /* Send the packet, and wait for it to leave. */
925 packet_send();
926 packet_write_wait();
927
928 /* Read response from the server. */
54a5250f 929 type = packet_read();
4fe2af09 930 if (type == SSH_SMSG_SUCCESS) {
5260325f 931 interactive = 1;
8ce64345 932 have_tty = 1;
4fe2af09 933 } else if (type == SSH_SMSG_FAILURE)
bbe88b6d 934 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
5260325f 935 else
936 packet_disconnect("Protocol error waiting for pty request response.");
937 }
938 /* Request X11 forwarding if enabled and DISPLAY is set. */
939 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
b48eeb07 940 char *proto, *data;
0b242b12 941 /* Get reasonable local authentication information. */
b48eeb07 942 x11_get_proto(&proto, &data);
0b242b12 943 /* Request forwarding with authentication spoofing. */
5260325f 944 debug("Requesting X11 forwarding with authentication spoofing.");
0b242b12 945 x11_request_forwarding_with_spoofing(0, proto, data);
5260325f 946
947 /* Read response from the server. */
54a5250f 948 type = packet_read();
5260325f 949 if (type == SSH_SMSG_SUCCESS) {
5260325f 950 interactive = 1;
0b242b12 951 } else if (type == SSH_SMSG_FAILURE) {
bbe88b6d 952 logit("Warning: Remote host denied X11 forwarding.");
0b242b12 953 } else {
5260325f 954 packet_disconnect("Protocol error waiting for X11 forwarding");
0b242b12 955 }
5260325f 956 }
957 /* Tell the packet module whether this is an interactive session. */
b5c334cc 958 packet_set_interactive(interactive);
5260325f 959
960 /* Request authentication agent forwarding if appropriate. */
fa08c86b 961 check_agent_present();
962
5260325f 963 if (options.forward_agent) {
964 debug("Requesting authentication agent forwarding.");
965 auth_request_forwarding();
966
967 /* Read response from the server. */
54a5250f 968 type = packet_read();
95500969 969 packet_check_eom();
5260325f 970 if (type != SSH_SMSG_SUCCESS)
bbe88b6d 971 logit("Warning: Remote host denied authentication agent forwarding.");
5260325f 972 }
8efc0c15 973
fa08c86b 974 /* Initiate port forwardings. */
975 ssh_init_forwarding();
5260325f 976
aa3378df 977 /* If requested, let ssh continue in the background. */
6ae2364d 978 if (fork_after_authentication_flag)
aa3378df 979 if (daemon(1, 1) < 0)
980 fatal("daemon() failed: %.200s", strerror(errno));
981
982 /*
983 * If a command was specified on the command line, execute the
984 * command now. Otherwise request the server to start a shell.
985 */
5260325f 986 if (buffer_len(&command) > 0) {
987 int len = buffer_len(&command);
988 if (len > 900)
989 len = 900;
6c0fa2b1 990 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
5260325f 991 packet_start(SSH_CMSG_EXEC_CMD);
992 packet_put_string(buffer_ptr(&command), buffer_len(&command));
993 packet_send();
994 packet_write_wait();
995 } else {
996 debug("Requesting shell.");
997 packet_start(SSH_CMSG_EXEC_SHELL);
998 packet_send();
999 packet_write_wait();
1000 }
1001
1002 /* Enter the interactive session. */
4bf9c10e 1003 return client_loop(have_tty, tty_flag ?
1004 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
8ce64345 1005}
5260325f 1006
396c147e 1007static void
5e96b616 1008ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1f3bf5aa 1009{
1010 int id, len;
1011
1012 id = packet_get_int();
1013 len = buffer_len(&command);
ce91d6f8 1014 if (len > 900)
1015 len = 900;
95500969 1016 packet_check_eom();
1f3bf5aa 1017 if (type == SSH2_MSG_CHANNEL_FAILURE)
1018 fatal("Request for subsystem '%.*s' failed on channel %d",
6c0fa2b1 1019 len, (u_char *)buffer_ptr(&command), id);
1f3bf5aa 1020}
1021
e0ae8728 1022void
5d8d32a3 1023client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
e0ae8728 1024{
1025 int i;
1026
1027 i = client_global_request_id++;
5d8d32a3 1028 if (i >= options.num_remote_forwards)
e0ae8728 1029 return;
e0ae8728 1030 debug("remote forward %s for: listen %d, connect %s:%d",
1031 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1032 options.remote_forwards[i].port,
1033 options.remote_forwards[i].host,
1034 options.remote_forwards[i].host_port);
1035 if (type == SSH2_MSG_REQUEST_FAILURE)
bbe88b6d 1036 logit("Warning: remote port forwarding failed for listen port %d",
e0ae8728 1037 options.remote_forwards[i].port);
1038}
1039
396c147e 1040static void
5e96b616 1041ssh_control_listener(void)
8ce64345 1042{
5e96b616 1043 struct sockaddr_un addr;
1044 mode_t old_umask;
4b5df124 1045 int addr_len;
1046
0d34d6ce 1047 if (options.control_path == NULL || options.control_master <= 0)
5e96b616 1048 return;
b5c334cc 1049
5e96b616 1050 memset(&addr, '\0', sizeof(addr));
1051 addr.sun_family = AF_UNIX;
4b5df124 1052 addr_len = offsetof(struct sockaddr_un, sun_path) +
5e96b616 1053 strlen(options.control_path) + 1;
8ce64345 1054
5e96b616 1055 if (strlcpy(addr.sun_path, options.control_path,
1056 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1057 fatal("ControlPath too long");
8ce64345 1058
5e96b616 1059 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1060 fatal("%s socket(): %s\n", __func__, strerror(errno));
1061
1062 old_umask = umask(0177);
4b5df124 1063 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
5e96b616 1064 control_fd = -1;
1065 if (errno == EINVAL)
1066 fatal("ControlSocket %s already exists",
1067 options.control_path);
1068 else
1069 fatal("%s bind(): %s\n", __func__, strerror(errno));
8ce64345 1070 }
5e96b616 1071 umask(old_umask);
1072
1073 if (listen(control_fd, 64) == -1)
1074 fatal("%s listen(): %s\n", __func__, strerror(errno));
1075
1076 set_nonblock(control_fd);
1077}
1078
1079/* request pty/x11/agent/tcpfwd/shell for channel */
1080static void
1081ssh_session2_setup(int id, void *arg)
1082{
1786be35 1083 extern char **environ;
1084
5e96b616 1085 int interactive = tty_flag;
1086 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
b48eeb07 1087 char *proto, *data;
0b242b12 1088 /* Get reasonable local authentication information. */
b48eeb07 1089 x11_get_proto(&proto, &data);
0b242b12 1090 /* Request forwarding with authentication spoofing. */
1091 debug("Requesting X11 forwarding with authentication spoofing.");
1092 x11_request_forwarding_with_spoofing(id, proto, data);
b5c334cc 1093 interactive = 1;
0b242b12 1094 /* XXX wait for reply */
1095 }
1096
fa08c86b 1097 check_agent_present();
1098 if (options.forward_agent) {
1099 debug("Requesting authentication agent forwarding.");
1100 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1101 packet_send();
1102 }
1103
5e96b616 1104 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1786be35 1105 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1f3bf5aa 1106
b5c334cc 1107 packet_set_interactive(interactive);
8ce64345 1108}
1109
bcdb96c2 1110/* open new channel for a session */
396c147e 1111static int
bcdb96c2 1112ssh_session2_open(void)
8ce64345 1113{
719fc62f 1114 Channel *c;
1115 int window, packetmax, in, out, err;
2e73a022 1116
14a9a859 1117 if (stdin_null_flag) {
5ca51e19 1118 in = open(_PATH_DEVNULL, O_RDONLY);
14a9a859 1119 } else {
1120 in = dup(STDIN_FILENO);
1121 }
2e73a022 1122 out = dup(STDOUT_FILENO);
1123 err = dup(STDERR_FILENO);
8ce64345 1124
1125 if (in < 0 || out < 0 || err < 0)
14a9a859 1126 fatal("dup() in/out/err failed");
8ce64345 1127
a22aff1f 1128 /* enable nonblocking unless tty */
1129 if (!isatty(in))
1130 set_nonblock(in);
1131 if (!isatty(out))
1132 set_nonblock(out);
1133 if (!isatty(err))
1134 set_nonblock(err);
1135
bcbf86ec 1136 window = CHAN_SES_WINDOW_DEFAULT;
1137 packetmax = CHAN_SES_PACKET_DEFAULT;
ea9700ba 1138 if (tty_flag) {
1139 window >>= 1;
1140 packetmax >>= 1;
8ce64345 1141 }
719fc62f 1142 c = channel_new(
8ce64345 1143 "session", SSH_CHANNEL_OPENING, in, out, err,
bcbf86ec 1144 window, packetmax, CHAN_EXTENDED_WRITE,
0d942eff 1145 "client-session", /*nonblock*/0);
8ce64345 1146
bcdb96c2 1147 debug3("ssh_session2_open: channel_new: %d", c->self);
eb0dd41f 1148
36e1f6a1 1149 channel_send_open(c->self);
bcdb96c2 1150 if (!no_shell_flag)
5e96b616 1151 channel_register_confirm(c->self, ssh_session2_setup, NULL);
5260325f 1152
719fc62f 1153 return c->self;
eb0dd41f 1154}
1155
396c147e 1156static int
eb0dd41f 1157ssh_session2(void)
1158{
bcdb96c2 1159 int id = -1;
eb0dd41f 1160
1161 /* XXX should be pre-session */
1162 ssh_init_forwarding();
5e96b616 1163 ssh_control_listener();
eb0dd41f 1164
bcdb96c2 1165 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1166 id = ssh_session2_open();
eb0dd41f 1167
1168 /* If requested, let ssh continue in the background. */
1169 if (fork_after_authentication_flag)
1170 if (daemon(1, 1) < 0)
1171 fatal("daemon() failed: %.200s", strerror(errno));
1172
4bf9c10e 1173 return client_loop(tty_flag, tty_flag ?
1174 options.escape_char : SSH_ESCAPECHAR_NONE, id);
8efc0c15 1175}
fa08c86b 1176
396c147e 1177static void
fee56204 1178load_public_identity_files(void)
1179{
1180 char *filename;
2e23cde0 1181 int i = 0;
0659cace 1182 Key *public;
383546c4 1183#ifdef SMARTCARD
0659cace 1184 Key **keys;
1185
9ff6f66f 1186 if (options.smartcard_device != NULL &&
0659cace 1187 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1188 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1189 int count = 0;
1190 for (i = 0; keys[i] != NULL; i++) {
1191 count++;
0659cace 1192 memmove(&options.identity_files[1], &options.identity_files[0],
1193 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1194 memmove(&options.identity_keys[1], &options.identity_keys[0],
1195 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1196 options.num_identity_files++;
1197 options.identity_keys[0] = keys[i];
244e796f 1198 options.identity_files[0] = sc_get_key_label(keys[i]);
0659cace 1199 }
1c2deed1 1200 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1201 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
0659cace 1202 i = count;
1203 xfree(keys);
383546c4 1204 }
3e984472 1205#endif /* SMARTCARD */
2e23cde0 1206 for (; i < options.num_identity_files; i++) {
1207 filename = tilde_expand_filename(options.identity_files[i],
1208 original_real_uid);
1209 public = key_load_public(filename, NULL);
1210 debug("identity file %s type %d", filename,
1211 public ? public->type : -1);
1212 xfree(options.identity_files[i]);
1213 options.identity_files[i] = filename;
1214 options.identity_keys[i] = public;
1215 }
fee56204 1216}
5e96b616 1217
1218static void
1219control_client_sighandler(int signo)
1220{
1221 control_client_terminate = signo;
1222}
1223
1224static void
1225control_client_sigrelay(int signo)
1226{
1227 if (control_server_pid > 1)
1228 kill(control_server_pid, signo);
1229}
1230
1231static void
1232control_client(const char *path)
1233{
1234 struct sockaddr_un addr;
1786be35 1235 int i, r, sock, exitval, addr_len;
5e96b616 1236 Buffer m;
1237 char *cp;
1786be35 1238 extern char **environ;
5e96b616 1239
1240 memset(&addr, '\0', sizeof(addr));
1241 addr.sun_family = AF_UNIX;
4b5df124 1242 addr_len = offsetof(struct sockaddr_un, sun_path) +
5e96b616 1243 strlen(path) + 1;
1244
1245 if (strlcpy(addr.sun_path, path,
1246 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1247 fatal("ControlPath too long");
1248
1249 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1250 fatal("%s socket(): %s", __func__, strerror(errno));
1251
4b5df124 1252 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1)
5e96b616 1253 fatal("Couldn't connect to %s: %s", path, strerror(errno));
1254
1255 if ((cp = getenv("TERM")) == NULL)
1256 cp = "";
1257
1258 signal(SIGINT, control_client_sighandler);
1259 signal(SIGTERM, control_client_sighandler);
1260 signal(SIGWINCH, control_client_sigrelay);
1261
1262 buffer_init(&m);
1263
1264 /* Get PID of controlee */
1265 if (ssh_msg_recv(sock, &m) == -1)
1266 fatal("%s: msg_recv", __func__);
1267 if (buffer_get_char(&m) != 0)
1268 fatal("%s: wrong version", __func__);
0d34d6ce 1269 /* Connection allowed? */
1270 if (buffer_get_int(&m) != 1)
1271 fatal("Connection to master denied");
5e96b616 1272 control_server_pid = buffer_get_int(&m);
1273
5e96b616 1274 buffer_clear(&m);
1275 buffer_put_int(&m, tty_flag);
1276 buffer_put_int(&m, subsystem_flag);
1277 buffer_put_cstring(&m, cp);
1278
1279 buffer_append(&command, "\0", 1);
1280 buffer_put_cstring(&m, buffer_ptr(&command));
1281
1786be35 1282 /* Pass environment */
1283 for (i = 0; environ != NULL && environ[i] != NULL; i++)
1284 ;
1285 buffer_put_int(&m, i);
1286 for (i = 0; environ != NULL && environ[i] != NULL; i++)
1287 buffer_put_cstring(&m, environ[i]);
1288
5e96b616 1289 if (ssh_msg_send(sock, /* version */0, &m) == -1)
1290 fatal("%s: msg_send", __func__);
1291
1292 mm_send_fd(sock, STDIN_FILENO);
1293 mm_send_fd(sock, STDOUT_FILENO);
1294 mm_send_fd(sock, STDERR_FILENO);
1295
1296 /* Wait for reply, so master has a chance to gather ttymodes */
1297 buffer_clear(&m);
1298 if (ssh_msg_recv(sock, &m) == -1)
1299 fatal("%s: msg_recv", __func__);
1300 if (buffer_get_char(&m) != 0)
1301 fatal("%s: master returned error", __func__);
1302 buffer_free(&m);
1303
1304 if (tty_flag)
1305 enter_raw_mode();
1306
1307 /* Stick around until the controlee closes the client_fd */
1308 exitval = 0;
1309 for (;!control_client_terminate;) {
1310 r = read(sock, &exitval, sizeof(exitval));
1311 if (r == 0) {
1312 debug2("Received EOF from master");
1313 break;
1314 }
1315 if (r > 0)
1316 debug2("Received exit status from master %d", exitval);
1317 if (r == -1 && errno != EINTR)
1318 fatal("%s: read %s", __func__, strerror(errno));
1319 }
1320
1321 if (control_client_terminate)
1322 debug2("Exiting on signal %d", control_client_terminate);
1323
1324 close(sock);
1325
1326 leave_raw_mode();
1327
1328 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1329 fprintf(stderr, "Connection to master closed.\r\n");
1330
1331 exit(exitval);
1332}
This page took 0.47327 seconds and 5 git commands to generate.