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