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