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