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