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