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