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