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