]> andersk Git - openssh.git/blame - ssh.c
- stevesk@cvs.openbsd.org 2006/07/11 20:16:43
[openssh.git] / ssh.c
CommitLineData
00c8971b 1/* $OpenBSD: ssh.c,v 1.284 2006/07/11 20:16:43 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 }
42ea6f5e 820 if (i > 0 && success != i && options.exit_on_forward_failure)
821 fatal("Could not request local forwarding.");
02a024dd 822 if (i > 0 && success == 0)
823 error("Could not request local forwarding.");
fa08c86b 824
825 /* Initiate remote TCP/IP port forwardings. */
826 for (i = 0; i < options.num_remote_forwards; i++) {
3867aa0a 827 debug("Remote connections from %.200s:%d forwarded to "
828 "local address %.200s:%d",
56964485 829 (options.remote_forwards[i].listen_host == NULL) ?
aa9bc1de 830 "LOCALHOST" : options.remote_forwards[i].listen_host,
3867aa0a 831 options.remote_forwards[i].listen_port,
832 options.remote_forwards[i].connect_host,
833 options.remote_forwards[i].connect_port);
42ea6f5e 834 if (channel_request_remote_forwarding(
3867aa0a 835 options.remote_forwards[i].listen_host,
836 options.remote_forwards[i].listen_port,
837 options.remote_forwards[i].connect_host,
42ea6f5e 838 options.remote_forwards[i].connect_port) < 0) {
839 if (options.exit_on_forward_failure)
840 fatal("Could not request remote forwarding.");
841 else
842 logit("Warning: Could not request remote "
843 "forwarding.");
844 }
fa08c86b 845 }
846}
847
396c147e 848static void
fa08c86b 849check_agent_present(void)
850{
851 if (options.forward_agent) {
7b9b0103 852 /* Clear agent forwarding if we don't have an agent. */
8b10e20e 853 if (!ssh_agent_present())
fa08c86b 854 options.forward_agent = 0;
fa08c86b 855 }
856}
857
396c147e 858static int
8ce64345 859ssh_session(void)
860{
861 int type;
8ce64345 862 int interactive = 0;
863 int have_tty = 0;
864 struct winsize ws;
8ce64345 865 char *cp;
9bf083eb 866 const char *display;
8ce64345 867
5260325f 868 /* Enable compression if requested. */
869 if (options.compression) {
870 debug("Requesting compression at level %d.", options.compression_level);
871
872 if (options.compression_level < 1 || options.compression_level > 9)
873 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
874
875 /* Send the request. */
876 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
877 packet_put_int(options.compression_level);
878 packet_send();
879 packet_write_wait();
54a5250f 880 type = packet_read();
5260325f 881 if (type == SSH_SMSG_SUCCESS)
882 packet_start_compression(options.compression_level);
883 else if (type == SSH_SMSG_FAILURE)
bbe88b6d 884 logit("Warning: Remote host refused compression.");
5260325f 885 else
886 packet_disconnect("Protocol error waiting for compression response.");
887 }
888 /* Allocate a pseudo tty if appropriate. */
889 if (tty_flag) {
890 debug("Requesting pty.");
891
892 /* Start the packet. */
893 packet_start(SSH_CMSG_REQUEST_PTY);
894
895 /* Store TERM in the packet. There is no limit on the
896 length of the string. */
897 cp = getenv("TERM");
898 if (!cp)
899 cp = "";
449c5ba5 900 packet_put_cstring(cp);
5260325f 901
902 /* Store window size in the packet. */
903 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
904 memset(&ws, 0, sizeof(ws));
148de80c 905 packet_put_int((u_int)ws.ws_row);
906 packet_put_int((u_int)ws.ws_col);
907 packet_put_int((u_int)ws.ws_xpixel);
908 packet_put_int((u_int)ws.ws_ypixel);
5260325f 909
910 /* Store tty modes in the packet. */
30dcc918 911 tty_make_modes(fileno(stdin), NULL);
5260325f 912
913 /* Send the packet, and wait for it to leave. */
914 packet_send();
915 packet_write_wait();
916
917 /* Read response from the server. */
54a5250f 918 type = packet_read();
4fe2af09 919 if (type == SSH_SMSG_SUCCESS) {
5260325f 920 interactive = 1;
8ce64345 921 have_tty = 1;
4fe2af09 922 } else if (type == SSH_SMSG_FAILURE)
bbe88b6d 923 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
5260325f 924 else
925 packet_disconnect("Protocol error waiting for pty request response.");
926 }
927 /* Request X11 forwarding if enabled and DISPLAY is set. */
9bf083eb 928 display = getenv("DISPLAY");
929 if (options.forward_x11 && display != NULL) {
b48eeb07 930 char *proto, *data;
0b242b12 931 /* Get reasonable local authentication information. */
9bf083eb 932 client_x11_get_proto(display, options.xauth_location,
933 options.forward_x11_trusted, &proto, &data);
0b242b12 934 /* Request forwarding with authentication spoofing. */
5260325f 935 debug("Requesting X11 forwarding with authentication spoofing.");
9bf083eb 936 x11_request_forwarding_with_spoofing(0, display, proto, data);
5260325f 937
938 /* Read response from the server. */
54a5250f 939 type = packet_read();
5260325f 940 if (type == SSH_SMSG_SUCCESS) {
5260325f 941 interactive = 1;
0b242b12 942 } else if (type == SSH_SMSG_FAILURE) {
bbe88b6d 943 logit("Warning: Remote host denied X11 forwarding.");
0b242b12 944 } else {
5260325f 945 packet_disconnect("Protocol error waiting for X11 forwarding");
0b242b12 946 }
5260325f 947 }
948 /* Tell the packet module whether this is an interactive session. */
b5c334cc 949 packet_set_interactive(interactive);
5260325f 950
951 /* Request authentication agent forwarding if appropriate. */
fa08c86b 952 check_agent_present();
953
5260325f 954 if (options.forward_agent) {
955 debug("Requesting authentication agent forwarding.");
956 auth_request_forwarding();
957
958 /* Read response from the server. */
54a5250f 959 type = packet_read();
95500969 960 packet_check_eom();
5260325f 961 if (type != SSH_SMSG_SUCCESS)
bbe88b6d 962 logit("Warning: Remote host denied authentication agent forwarding.");
5260325f 963 }
8efc0c15 964
fa08c86b 965 /* Initiate port forwardings. */
966 ssh_init_forwarding();
5260325f 967
aa3378df 968 /* If requested, let ssh continue in the background. */
6ae2364d 969 if (fork_after_authentication_flag)
aa3378df 970 if (daemon(1, 1) < 0)
971 fatal("daemon() failed: %.200s", strerror(errno));
972
973 /*
974 * If a command was specified on the command line, execute the
975 * command now. Otherwise request the server to start a shell.
976 */
5260325f 977 if (buffer_len(&command) > 0) {
978 int len = buffer_len(&command);
979 if (len > 900)
980 len = 900;
6c0fa2b1 981 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
5260325f 982 packet_start(SSH_CMSG_EXEC_CMD);
983 packet_put_string(buffer_ptr(&command), buffer_len(&command));
984 packet_send();
985 packet_write_wait();
986 } else {
987 debug("Requesting shell.");
988 packet_start(SSH_CMSG_EXEC_SHELL);
989 packet_send();
990 packet_write_wait();
991 }
992
993 /* Enter the interactive session. */
4bf9c10e 994 return client_loop(have_tty, tty_flag ?
995 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
8ce64345 996}
5260325f 997
396c147e 998static void
5e96b616 999ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1f3bf5aa 1000{
1001 int id, len;
1002
1003 id = packet_get_int();
1004 len = buffer_len(&command);
ce91d6f8 1005 if (len > 900)
1006 len = 900;
95500969 1007 packet_check_eom();
1f3bf5aa 1008 if (type == SSH2_MSG_CHANNEL_FAILURE)
1009 fatal("Request for subsystem '%.*s' failed on channel %d",
6c0fa2b1 1010 len, (u_char *)buffer_ptr(&command), id);
1f3bf5aa 1011}
1012
e0ae8728 1013void
5d8d32a3 1014client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
e0ae8728 1015{
1016 int i;
1017
1018 i = client_global_request_id++;
5d8d32a3 1019 if (i >= options.num_remote_forwards)
e0ae8728 1020 return;
e0ae8728 1021 debug("remote forward %s for: listen %d, connect %s:%d",
1022 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
3867aa0a 1023 options.remote_forwards[i].listen_port,
1024 options.remote_forwards[i].connect_host,
1025 options.remote_forwards[i].connect_port);
42ea6f5e 1026 if (type == SSH2_MSG_REQUEST_FAILURE) {
1027 if (options.exit_on_forward_failure)
1028 fatal("Error: remote port forwarding failed for "
1029 "listen port %d",
1030 options.remote_forwards[i].listen_port);
1031 else
1032 logit("Warning: remote port forwarding failed for "
1033 "listen port %d",
1034 options.remote_forwards[i].listen_port);
1035 }
e0ae8728 1036}
1037
396c147e 1038static void
5e96b616 1039ssh_control_listener(void)
8ce64345 1040{
5e96b616 1041 struct sockaddr_un addr;
1042 mode_t old_umask;
4b5df124 1043 int addr_len;
1044
9dfd96d6 1045 if (options.control_path == NULL ||
1046 options.control_master == SSHCTL_MASTER_NO)
5e96b616 1047 return;
b5c334cc 1048
9dfd96d6 1049 debug("setting up multiplex master socket");
1050
5e96b616 1051 memset(&addr, '\0', sizeof(addr));
1052 addr.sun_family = AF_UNIX;
4b5df124 1053 addr_len = offsetof(struct sockaddr_un, sun_path) +
5e96b616 1054 strlen(options.control_path) + 1;
8ce64345 1055
5e96b616 1056 if (strlcpy(addr.sun_path, options.control_path,
1057 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1058 fatal("ControlPath too long");
8ce64345 1059
5e96b616 1060 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
17318dd6 1061 fatal("%s socket(): %s", __func__, strerror(errno));
5e96b616 1062
1063 old_umask = umask(0177);
32596c7b 1064 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
5e96b616 1065 control_fd = -1;
05ada1a6 1066 if (errno == EINVAL || errno == EADDRINUSE)
5e96b616 1067 fatal("ControlSocket %s already exists",
1068 options.control_path);
1069 else
17318dd6 1070 fatal("%s bind(): %s", __func__, strerror(errno));
8ce64345 1071 }
5e96b616 1072 umask(old_umask);
1073
1074 if (listen(control_fd, 64) == -1)
17318dd6 1075 fatal("%s listen(): %s", __func__, strerror(errno));
5e96b616 1076
1077 set_nonblock(control_fd);
1078}
1079
1080/* request pty/x11/agent/tcpfwd/shell for channel */
1081static void
1082ssh_session2_setup(int id, void *arg)
1083{
1786be35 1084 extern char **environ;
9bf083eb 1085 const char *display;
5e96b616 1086 int interactive = tty_flag;
9bf083eb 1087
56964485 1088 display = getenv("DISPLAY");
9bf083eb 1089 if (options.forward_x11 && display != NULL) {
b48eeb07 1090 char *proto, *data;
0b242b12 1091 /* Get reasonable local authentication information. */
9bf083eb 1092 client_x11_get_proto(display, options.xauth_location,
1093 options.forward_x11_trusted, &proto, &data);
0b242b12 1094 /* Request forwarding with authentication spoofing. */
1095 debug("Requesting X11 forwarding with authentication spoofing.");
9bf083eb 1096 x11_request_forwarding_with_spoofing(id, display, proto, data);
b5c334cc 1097 interactive = 1;
0b242b12 1098 /* XXX wait for reply */
1099 }
1100
fa08c86b 1101 check_agent_present();
1102 if (options.forward_agent) {
1103 debug("Requesting authentication agent forwarding.");
1104 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1105 packet_send();
1106 }
1107
a4f24bf8 1108 if (options.tun_open != SSH_TUNMODE_NO) {
d20f3c9e 1109 Channel *c;
1110 int fd;
1111
1112 debug("Requesting tun.");
a4f24bf8 1113 if ((fd = tun_open(options.tun_local,
1114 options.tun_open)) >= 0) {
d20f3c9e 1115 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1116 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1117 0, "tun", 1);
1118 c->datagram = 1;
e914f53a 1119#if defined(SSH_TUN_FILTER)
1120 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1121 channel_register_filter(c->self, sys_tun_infilter,
1122 sys_tun_outfilter);
1123#endif
d20f3c9e 1124 packet_start(SSH2_MSG_CHANNEL_OPEN);
1125 packet_put_cstring("tun@openssh.com");
1126 packet_put_int(c->self);
1127 packet_put_int(c->local_window_max);
1128 packet_put_int(c->local_maxpacket);
a4f24bf8 1129 packet_put_int(options.tun_open);
d20f3c9e 1130 packet_put_int(options.tun_remote);
1131 packet_send();
1132 }
1133 }
1134
5e96b616 1135 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1786be35 1136 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1f3bf5aa 1137
b5c334cc 1138 packet_set_interactive(interactive);
8ce64345 1139}
1140
bcdb96c2 1141/* open new channel for a session */
396c147e 1142static int
bcdb96c2 1143ssh_session2_open(void)
8ce64345 1144{
719fc62f 1145 Channel *c;
1146 int window, packetmax, in, out, err;
2e73a022 1147
14a9a859 1148 if (stdin_null_flag) {
5ca51e19 1149 in = open(_PATH_DEVNULL, O_RDONLY);
14a9a859 1150 } else {
1151 in = dup(STDIN_FILENO);
1152 }
2e73a022 1153 out = dup(STDOUT_FILENO);
1154 err = dup(STDERR_FILENO);
8ce64345 1155
1156 if (in < 0 || out < 0 || err < 0)
14a9a859 1157 fatal("dup() in/out/err failed");
8ce64345 1158
a22aff1f 1159 /* enable nonblocking unless tty */
1160 if (!isatty(in))
1161 set_nonblock(in);
1162 if (!isatty(out))
1163 set_nonblock(out);
1164 if (!isatty(err))
1165 set_nonblock(err);
1166
bcbf86ec 1167 window = CHAN_SES_WINDOW_DEFAULT;
1168 packetmax = CHAN_SES_PACKET_DEFAULT;
ea9700ba 1169 if (tty_flag) {
1170 window >>= 1;
1171 packetmax >>= 1;
8ce64345 1172 }
719fc62f 1173 c = channel_new(
8ce64345 1174 "session", SSH_CHANNEL_OPENING, in, out, err,
bcbf86ec 1175 window, packetmax, CHAN_EXTENDED_WRITE,
0d942eff 1176 "client-session", /*nonblock*/0);
8ce64345 1177
bcdb96c2 1178 debug3("ssh_session2_open: channel_new: %d", c->self);
eb0dd41f 1179
36e1f6a1 1180 channel_send_open(c->self);
bcdb96c2 1181 if (!no_shell_flag)
5e96b616 1182 channel_register_confirm(c->self, ssh_session2_setup, NULL);
5260325f 1183
719fc62f 1184 return c->self;
eb0dd41f 1185}
1186
396c147e 1187static int
eb0dd41f 1188ssh_session2(void)
1189{
bcdb96c2 1190 int id = -1;
eb0dd41f 1191
1192 /* XXX should be pre-session */
1193 ssh_init_forwarding();
5e96b616 1194 ssh_control_listener();
eb0dd41f 1195
bcdb96c2 1196 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1197 id = ssh_session2_open();
eb0dd41f 1198
d20f3c9e 1199 /* Execute a local command */
1200 if (options.local_command != NULL &&
1201 options.permit_local_command)
1202 ssh_local_cmd(options.local_command);
1203
eb0dd41f 1204 /* If requested, let ssh continue in the background. */
1205 if (fork_after_authentication_flag)
1206 if (daemon(1, 1) < 0)
1207 fatal("daemon() failed: %.200s", strerror(errno));
1208
4bf9c10e 1209 return client_loop(tty_flag, tty_flag ?
1210 options.escape_char : SSH_ESCAPECHAR_NONE, id);
8efc0c15 1211}
fa08c86b 1212
396c147e 1213static void
fee56204 1214load_public_identity_files(void)
1215{
8cffe22a 1216 char *filename, *cp, thishost[NI_MAXHOST];
2e23cde0 1217 int i = 0;
0659cace 1218 Key *public;
8cffe22a 1219 struct passwd *pw;
383546c4 1220#ifdef SMARTCARD
0659cace 1221 Key **keys;
1222
9ff6f66f 1223 if (options.smartcard_device != NULL &&
0659cace 1224 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1225 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1226 int count = 0;
1227 for (i = 0; keys[i] != NULL; i++) {
1228 count++;
0659cace 1229 memmove(&options.identity_files[1], &options.identity_files[0],
1230 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1231 memmove(&options.identity_keys[1], &options.identity_keys[0],
1232 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1233 options.num_identity_files++;
1234 options.identity_keys[0] = keys[i];
244e796f 1235 options.identity_files[0] = sc_get_key_label(keys[i]);
0659cace 1236 }
1c2deed1 1237 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1238 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
0659cace 1239 i = count;
1240 xfree(keys);
383546c4 1241 }
3e984472 1242#endif /* SMARTCARD */
8cffe22a 1243 if ((pw = getpwuid(original_real_uid)) == NULL)
1244 fatal("load_public_identity_files: getpwuid failed");
1245 if (gethostname(thishost, sizeof(thishost)) == -1)
1246 fatal("load_public_identity_files: gethostname: %s",
1247 strerror(errno));
2e23cde0 1248 for (; i < options.num_identity_files; i++) {
8cffe22a 1249 cp = tilde_expand_filename(options.identity_files[i],
2e23cde0 1250 original_real_uid);
8cffe22a 1251 filename = percent_expand(cp, "d", pw->pw_dir,
1252 "u", pw->pw_name, "l", thishost, "h", host,
1253 "r", options.user, (char *)NULL);
1254 xfree(cp);
2e23cde0 1255 public = key_load_public(filename, NULL);
1256 debug("identity file %s type %d", filename,
1257 public ? public->type : -1);
1258 xfree(options.identity_files[i]);
1259 options.identity_files[i] = filename;
1260 options.identity_keys[i] = public;
1261 }
fee56204 1262}
5e96b616 1263
1264static void
1265control_client_sighandler(int signo)
1266{
1267 control_client_terminate = signo;
1268}
1269
1270static void
1271control_client_sigrelay(int signo)
1272{
1273 if (control_server_pid > 1)
1274 kill(control_server_pid, signo);
1275}
1276
67a08279 1277static int
1278env_permitted(char *env)
1279{
0ad62016 1280 int i, ret;
67a08279 1281 char name[1024], *cp;
1282
0ad62016 1283 if ((cp = strchr(env, '=')) == NULL || cp == env)
67a08279 1284 return (0);
00c8971b 1285 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
0ad62016 1286 if (ret <= 0 || (size_t)ret >= sizeof(name))
1287 fatal("env_permitted: name '%.100s...' too long", env);
67a08279 1288
1289 for (i = 0; i < options.num_send_env; i++)
1290 if (match_pattern(name, options.send_env[i]))
1291 return (1);
1292
1293 return (0);
1294}
1295
5e96b616 1296static void
1297control_client(const char *path)
1298{
1299 struct sockaddr_un addr;
a7e124fe 1300 int i, r, fd, sock, exitval, num_env, addr_len;
5e96b616 1301 Buffer m;
f8c6db83 1302 char *term;
1786be35 1303 extern char **environ;
f8c6db83 1304 u_int flags;
f2107e97 1305
9dfd96d6 1306 if (mux_command == 0)
1307 mux_command = SSHMUX_COMMAND_OPEN;
1308
1309 switch (options.control_master) {
1310 case SSHCTL_MASTER_AUTO:
1311 case SSHCTL_MASTER_AUTO_ASK:
1312 debug("auto-mux: Trying existing master");
1313 /* FALLTHROUGH */
1314 case SSHCTL_MASTER_NO:
1315 break;
1316 default:
1317 return;
1318 }
1319
5e96b616 1320 memset(&addr, '\0', sizeof(addr));
1321 addr.sun_family = AF_UNIX;
4b5df124 1322 addr_len = offsetof(struct sockaddr_un, sun_path) +
5e96b616 1323 strlen(path) + 1;
1324
1325 if (strlcpy(addr.sun_path, path,
1326 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1327 fatal("ControlPath too long");
1328
1329 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1330 fatal("%s socket(): %s", __func__, strerror(errno));
1331
32596c7b 1332 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
19186c3d 1333 if (mux_command != SSHMUX_COMMAND_OPEN) {
1334 fatal("Control socket connect(%.100s): %s", path,
1335 strerror(errno));
1336 }
f6740270 1337 if (errno == ENOENT)
7de98c39 1338 debug("Control socket \"%.100s\" does not exist", path);
f6740270 1339 else {
7de98c39 1340 error("Control socket connect(%.100s): %s", path,
f6740270 1341 strerror(errno));
1342 }
7de98c39 1343 close(sock);
1344 return;
1345 }
1346
1347 if (stdin_null_flag) {
1348 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1349 fatal("open(/dev/null): %s", strerror(errno));
1350 if (dup2(fd, STDIN_FILENO) == -1)
1351 fatal("dup2: %s", strerror(errno));
1352 if (fd > STDERR_FILENO)
1353 close(fd);
1354 }
56964485 1355
ef07103c 1356 term = getenv("TERM");
f8c6db83 1357
1358 flags = 0;
1359 if (tty_flag)
1360 flags |= SSHMUX_FLAG_TTY;
1361 if (subsystem_flag)
1362 flags |= SSHMUX_FLAG_SUBSYS;
ef07103c 1363 if (options.forward_x11)
1364 flags |= SSHMUX_FLAG_X11_FWD;
1365 if (options.forward_agent)
1366 flags |= SSHMUX_FLAG_AGENT_FWD;
5e96b616 1367
5e96b616 1368 buffer_init(&m);
1369
f8c6db83 1370 /* Send our command to server */
1371 buffer_put_int(&m, mux_command);
1372 buffer_put_int(&m, flags);
ef07103c 1373 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
f8c6db83 1374 fatal("%s: msg_send", __func__);
1375 buffer_clear(&m);
1376
1377 /* Get authorisation status and PID of controlee */
5e96b616 1378 if (ssh_msg_recv(sock, &m) == -1)
1379 fatal("%s: msg_recv", __func__);
ef07103c 1380 if (buffer_get_char(&m) != SSHMUX_VER)
5e96b616 1381 fatal("%s: wrong version", __func__);
0d34d6ce 1382 if (buffer_get_int(&m) != 1)
1383 fatal("Connection to master denied");
5e96b616 1384 control_server_pid = buffer_get_int(&m);
1385
5e96b616 1386 buffer_clear(&m);
5e96b616 1387
f8c6db83 1388 switch (mux_command) {
1389 case SSHMUX_COMMAND_ALIVE_CHECK:
f8cc7664 1390 fprintf(stderr, "Master running (pid=%d)\r\n",
f8c6db83 1391 control_server_pid);
1392 exit(0);
1393 case SSHMUX_COMMAND_TERMINATE:
1394 fprintf(stderr, "Exit request sent.\r\n");
1395 exit(0);
1396 case SSHMUX_COMMAND_OPEN:
1397 /* continue below */
1398 break;
1399 default:
1400 fatal("silly mux_command %d", mux_command);
1401 }
1402
1403 /* SSHMUX_COMMAND_OPEN */
ef07103c 1404 buffer_put_cstring(&m, term ? term : "");
5e96b616 1405 buffer_append(&command, "\0", 1);
1406 buffer_put_cstring(&m, buffer_ptr(&command));
1407
67a08279 1408 if (options.num_send_env == 0 || environ == NULL) {
1409 buffer_put_int(&m, 0);
f2107e97 1410 } else {
67a08279 1411 /* Pass environment */
1412 num_env = 0;
1413 for (i = 0; environ[i] != NULL; i++)
1414 if (env_permitted(environ[i]))
1415 num_env++; /* Count */
f2107e97 1416
67a08279 1417 buffer_put_int(&m, num_env);
1418
77c50919 1419 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1420 if (env_permitted(environ[i])) {
1421 num_env--;
67a08279 1422 buffer_put_cstring(&m, environ[i]);
77c50919 1423 }
67a08279 1424 }
1786be35 1425
ef07103c 1426 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
5e96b616 1427 fatal("%s: msg_send", __func__);
1428
1429 mm_send_fd(sock, STDIN_FILENO);
1430 mm_send_fd(sock, STDOUT_FILENO);
1431 mm_send_fd(sock, STDERR_FILENO);
1432
1433 /* Wait for reply, so master has a chance to gather ttymodes */
1434 buffer_clear(&m);
1435 if (ssh_msg_recv(sock, &m) == -1)
1436 fatal("%s: msg_recv", __func__);
ef07103c 1437 if (buffer_get_char(&m) != SSHMUX_VER)
f8c6db83 1438 fatal("%s: wrong version", __func__);
5e96b616 1439 buffer_free(&m);
1440
d3e5d1e9 1441 signal(SIGHUP, control_client_sighandler);
78d2b454 1442 signal(SIGINT, control_client_sighandler);
1443 signal(SIGTERM, control_client_sighandler);
1444 signal(SIGWINCH, control_client_sigrelay);
1445
5e96b616 1446 if (tty_flag)
1447 enter_raw_mode();
1448
1449 /* Stick around until the controlee closes the client_fd */
1450 exitval = 0;
1451 for (;!control_client_terminate;) {
1452 r = read(sock, &exitval, sizeof(exitval));
1453 if (r == 0) {
1454 debug2("Received EOF from master");
1455 break;
1456 }
1457 if (r > 0)
1458 debug2("Received exit status from master %d", exitval);
1459 if (r == -1 && errno != EINTR)
1460 fatal("%s: read %s", __func__, strerror(errno));
1461 }
1462
1463 if (control_client_terminate)
1464 debug2("Exiting on signal %d", control_client_terminate);
1465
1466 close(sock);
1467
1468 leave_raw_mode();
1469
1470 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1471 fprintf(stderr, "Connection to master closed.\r\n");
1472
1473 exit(exitval);
1474}
This page took 1.126255 seconds and 5 git commands to generate.