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